当前位置: 代码迷 >> Android >> ImageSwitcher cannot be cast to Button_ClassCastException,该如何解决
  详细解决方案

ImageSwitcher cannot be cast to Button_ClassCastException,该如何解决

热度:231   发布时间:2016-04-27 22:13:17.0
ImageSwitcher cannot be cast to Button_ClassCastException
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.imageswitcher.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="上一张" />

    <ImageSwitcher
        android:id="@+id/imageSwitcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下一张" />

</LinearLayout>

private Button button1, button2;
private ImageSwitcher imageSwitcher;
private int index = 0;
private int[] imageId = new int[] { R.drawable.landscape1,
R.drawable.landscape2, R.drawable.landscape3,
R.drawable.landscape4, R.drawable.landscape5,
R.drawable.landscape6, R.drawable.landscape7 };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
imageSwitcher = (ImageSwitcher) this.findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(this);

button1.setOnClickListener(this);
button2.setOnClickListener(this);
imageSwitcher.setImageResource(imageId[index]);
}

public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
index--;
if (index < 0) {
index = imageId.length - 1;
}
imageSwitcher.setImageResource(imageId[index]);
Toast.makeText(MainActivity.this, "第" + (index + 1) + "张", 1).show();
break;
case R.id.button2:
index++;
if (index >= imageId.length) {
index = 0;
}
imageSwitcher.setImageResource(imageId[index]);
Toast.makeText(MainActivity.this, "第" + (index + 1) + "张", 1).show();
break;
}
}

public View makeView() {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return imageView ;
}


实现的是通过两个按钮来前后查看图片, 用的是ImageSwitcher  
可是在xml文件中, 如果把ImageSwitcher标签放在Button上面就会报错如下图

ImageSwitcher cannot be cast to Button_ClassCastException  但是如果像上面xml文件中放置就可以正常运行,大神们知道这是为什么吗?





------解决思路----------------------
照理不会的,楼主自己检讨一下,先删除按钮保存一下, 再添加按钮到正确位置, 再保存一下

------解决思路----------------------
资源混淆了吧,clean一下工程,卸载掉apk重新安装下试试
------解决思路----------------------
clean一下,电脑慢改了XML经常这样,代码是木有问题的。
  相关解决方案