Sch*_*get 5 java android view classcastexception
尝试使用findViewById()获取自定义View时,我遇到了一个问题.否则,自定义视图将正确显示和运行.不幸的是,我需要能够随意更改它显示的一些数据,因此必须完成.
我的XML看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.TheProject.TheApp.Chart
android:id="@+id/chart"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
我知道有时问题是人们不小心在XML中命名组件"View"而不是它们的子类.
在我的Activity的onCreate()方法中,我有这个:
myChart=(Chart)findViewById(R.id.chart); //where myChart is an object of type Chart
Run Code Online (Sandbox Code Playgroud)
抛出ClassCastException.
我决定尝试一下,然后将行更改为此,以查看是否仍然收到ClassCastException:
View chart=(View)findViewById(R.id.chart);
Run Code Online (Sandbox Code Playgroud)
这很好用,告诉我findViewById给我一个View没有问题.但它不想给我一张图表.
就Chart类而言,它是View的一个非常简单的子类,看起来可以正常工作.
public class Chart extends View{
public Chart(Context context) {
super(context);
init();
}
public Chart(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Chart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/* More stuff below like onDraw, onMeasure, setData, etc. */
}
Run Code Online (Sandbox Code Playgroud)
我可能只是在做一些愚蠢的事情.你们有什么想法吗?谢谢你的帮助!
只是出于好奇,该 xml 是否正在另一个带有<include>标签的布局中使用?
我遇到了这样的问题,我们在 viewflipper 中包含另一个 xml 布局
<include layout="@layout/some_layout.xml">并且findviewbyid得到了错误的小部件。我必须将整个外部布局包装在<merge></merge>标签中,以使其能够正确合并到基本布局中。
如果包含的话,请尝试将您的布局更改为此。
<?xml version="1.0" encoding="utf-8"?>
<merge>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.TheProject.TheApp.Chart
android:id="@+id/chart"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
</merge>
Run Code Online (Sandbox Code Playgroud)
编辑:查看此链接了解合并的工作原理
| 归档时间: |
|
| 查看次数: |
1624 次 |
| 最近记录: |