我创建了一个自定义日历视图组,其中包括一个元素,可允许用户选择年度。此自定义视图将用于多个应用程序中,因此创建可以重复使用的AAR之类的东西是有意义的。我需要一些特定的样式,因此,无论我在何处部署它,视图看起来都一样。
我的自定义ViewGroup找到并呈现ViewGroup的主要布局。但是,当用户敲击年度旋转器并想更改年度时,适配器找不到下拉列表的文本ID。我已经检查了我的APK中的合并清单,并且可以看到AAR的布局和文本ID,但是它在点击时崩溃了:
java.lang.RuntimeException: Failed to find view with ID us.martypants.mycustomviewgroup:id/current_year in item layout
足够有趣的是,如果代替自定义布局,我使用android的布局(即android.r.layout.simple_spiner_item和android.r.id.text1(apk可以找到资源结果 - 尽管我不需要的样式。
自定义视图:
package com.algtskr.algtskrcommon
class DropdownAgeSelectView (context: Context, attrs: AttributeSet): RelativeLayout(context, attrs),
AdapterView.OnItemSelectedListener {
private var mCounterColor = 0
private var mAge = 0
init {
LayoutInflater.from(context)
.inflate(R.layout.dropdown_ageselect_layout, this, true)
attrs.let {
val typedArray = context.obtainStyledAttributes(it,
R.styleable.DropdownAgeSelectView, 0, 0)
mCounterColor = typedArray.getColor(R.styleable.DropdownAgeSelectView_counter_color, 0)
mAge = typedArray.getInteger(R.styleable.DropdownAgeSelectView_initial_value, 0)
typedArray.recycle()
}
val adapter = ArrayAdapter(context,R.layout.year_layout_text,R.id.current_year, childAgeList)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
spinner.onItemSelectedListener = this
initLayout()
}
yaly_layout_text.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/current_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingStart="10dp"
tools:text="2019"
android:textColor="@color/blue_passenger"
android:textSize="24sp"/>
使用此代码中的Android资源,APK可以看到资源,但它们未经风格:
val adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, android.R.id.text1, childAgeList)
使用我的自定义资源,apk无法找到资源ID,current_year,尽管它确实找到并使用了布局文件和样式,然后才能单击它
val adapter = ArrayAdapter(context,R.layout.year_layout_text,R.id.current_year, childAgeList)
知道为什么AAR正确找到并呈现整体ViewGroup布局,但是布局中的各个部分不是?为什么即使AAR显示在RES/文件夹中以及我的APK中显示它们,为什么还没有在APK中找到所有的布局和资源。
问题在这里:
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
当您将R.id.current_year
传递到ArrayAdapter
构造函数时,将用于折叠视图和弹出窗口中的每一行("下拉"视图(。由于您的下拉布局不包含ID R.id.current_year
的视图,因此您崩溃了。
更改此setDropDownViewResource()
调用,以使用您自己的自定义布局,包括R.id.current_year
TextView。
由于您将构造函数的R.id.current_year
作为适配器的TextView
样式传递,然后通过新布局不包含R.id.current_year
中的CC_8在新布局中找到R.id.current_yea
R。
删除将执行技巧