转换扩展视图以查看layoutinflater

时间:2014-11-12 18:30:30

标签: java android android-layout

我想要做的是能够拥有自己的自定义控件,它将具有一些属性。为此,我扩展了现有的View(RelativeView)并创建了我自己的视图。问题是,当我尝试通过inflater从xml布局获取相对视图时,我得到了java lang类的cast exeption。我怎么能避免这种情况?

MyRelativeView control = (MyRelativeView) LayoutInflater.from(getContext()).inflate(R.layout.something, null, false);

MyRelativeView扩展了RelativeLayout,而膨胀的视图是一个relativelayout。为什么我

java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to controls.MyRelativeView

1 个答案:

答案 0 :(得分:0)

您的布局文件中应包含自定义视图,您的视图会扩展相对视图,但relativeview不是myrelativeview。它应该是这样的:

<com.example.customviews.myRelativeView
     xmlns:android="http://schemas.android.com/apk/res/android"
     custom:showText="true"
     custom:labelPosition="left" 
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

    <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="Some text"
           android:paddingTop ="4dp"
           android:paddingBottom="4dp"
           android:id="@+id/textViewOne"
        />


    <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="Some text"
           android:paddingTop ="4dp"
           android:paddingBottom="4dp"
           android:id="@+id/textViewTwo"
        />
    </com.example.customviews.myRelativeView>