我有一个实际包装另一个组件的自定义组件。它的布局是:
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/text_view_background" android:textCursorDrawable="@null"
android:textColor="@android:color/black" android:inputType="textNoSuggestions"
android:paddingLeft="7dp"/>
在组件的代码中,我试图给它充气:
inflate(context,R.layout.results_auto_complete,this);
resultsAutoComplete=(AutoCompleteTextView)getChildAt(0);
但是我得到一个ClassCastException
,它说第一个孩子是RelativeLayout
!我追踪了这个相对布局的所有孩子,它实际上是小部件的布局,其配置活动包含我的自定义组件!当我使用简单的测试活动测试组件时,一切正常!
那么为什么会这样呢?我该怎么办呢? 感谢。
答案 0 :(得分:0)
如果AutoCompleteTextView
是results_auto_complete.xml
的独立xml文件(您的代码是根xml标记)。这是通货膨胀的结果,不需要使用getChildAt(i)。
如果<AutoCompleteTextView>
是XML文件中的子元素,则应使用id:android:id="@+id/your_view_id"
。然后在通货膨胀后,使用:
this.findViewById(R.your_view_id);
这是加载组件视图的当前活动。
更新,试试这个:
LayoutInflater mInflater = (LayoutInflater)etContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
resultsAutoComplete=(AutoCompleteTextView)mInflater.inflate(R.layout.your_view_id, this, true);
答案 1 :(得分:0)
似乎问题是我有2个布局,来自不同项目的标识符相同(一个项目链接到另一个项目),所以当我试图从其中一个项目中扩展布局时,我得到了另一个项目中具有相同标识符的布局。无论如何,感谢您的帮助。