【问题标题】:android cast to custom View : ClassCastException: android.widget.LinearLayoutandroid强制转换为自定义视图:ClassCastException:android.widget.LinearLayout
【发布时间】:2012-07-06 18:35:25
【问题描述】:

我得到 ClassCastException: android.widget.LinearLayout 我试图抓住这样一个事实,即视图(Lineralayout)中包含 listview 的元素(其中一个子视图)。

自定义视图:

public class MasterView extends View {
public boolean done=false;
public MasterView(Context context) {
    super(context);
}
public MasterView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MasterView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
    // TODO Auto-generated method stub
    done=true;
    super.onFinishInflate();
}

}

我这样称呼它:

View master = (View)findViewById(R.id.master);
MasterView master2 = (MasterView)master; //exception

xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/master"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
    android:id="@+id/cnt"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.03" >

</RelativeLayout>

</LinearLayout>

我用列表膨胀cnt

【问题讨论】:

  • R.id.master 是 LinearLayout 类型而不是 MasterView

标签: android casting


【解决方案1】:

xml 中的 R.id.master 元素不是 MasterView 类型。将您的 xml 更改为:

<yourpackage.MasterView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/master"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >
  <RelativeLayout
    android:id="@+id/cnt"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="0.03" >
  </RelativeLayout>
</yourpackage.MasterView>

【讨论】:

  • 扩展视图使我不得不从线性布局扩展的应用程序崩溃。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2023-03-05
相关资源
最近更新 更多