我有一个自定义组件,它实际上包装了另一个组件。它的布局是:
<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
!我跟踪了这个相对布局的所有子布局,它实际上是小部件的布局,它的配置活动包含我的自定义组件!当我用一个简单的测试活动测试组件时,一切都正常!
那么为什么会发生这种情况,我能做些什么呢?谢谢。
发布于 2012-11-02 13:33:24
似乎问题是我有两个来自不同项目的具有相同标识符的布局(一个项目链接到另一个项目),所以当我试图从其中一个项目膨胀布局时,我在另一个项目中获得了具有相同标识符的布局。不管怎样,谢谢你的帮助。
发布于 2012-11-02 07:21:53
如果您的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);
https://stackoverflow.com/questions/13190095
复制相似问题