错误:E/AndroidRuntime(6539): Caused by: java.lang.ClassCastException: android.widget.

来源:互联网 发布:安禄山史思明之死 知乎 编辑:程序博客网 时间:2024/05/22 17:50

错误提示::07-09 16:22:39.774: E/AndroidRuntime(6539): Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.FrameLayout

问题出现的原因:组件类型不一致,产生错误的代码如下:

1、布局文件中:布局使用RelativeLayout进行布局

<RelativeLayout 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:id="@+id/content"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.lutsoft.android_010_multouch.MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>
2、MainActivity类中代码如下所示:在MainActivity中使用FrameLayout组件来接收

package com.lutsoft.android_010_multouch;import android.app.Activity;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.FrameLayout;import android.widget.RelativeLayout;public class MainActivity extends Activity {private FrameLayout root;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);root=(FrameLayout) findViewById(R.id.content);root.setOnTouchListener(new OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:System.out.println("Action down");break;case MotionEvent.ACTION_MOVE:System.out.println("Action Move");break;case MotionEvent.ACTION_UP:System.out.println("Action up");break;default:break;}return false;}});}}
解决:解决办法是将MainActivity类中的FrameLayout改变为RelativeLayout组件进行接收(或者改变布局文件activity-main.xml文件中的布局,将RelativeLayout改变为FrameLayout)即可。此异常和Java中的类型转换异常类似。





1 0
原创粉丝点击