android.widget.TextView无法强制转换为android.view.ViewGroup0

时间:2015-09-21 12:42:13

标签: android android-layout android-studio android-widget textview

无法找到此错误的来源。 看到有关同一问题的其他问题,这通常是由于缺少结束标记引起的。但是在我的代码中找不到哪一个......

我的主要activity.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="horizontal">

<TextView
    android:text="@string/main_textview"
    android:layout_width="0px"
    android:layout_weight="2"
    android:background="#FFF8DC"
    android:padding="@dimen/component_padding"
    android:layout_height="match_parent" >
</TextView>

<TextView
    android:id="@+id/simplefragment"
    android:layout_width="0px"
    android:layout_weight="2"
    android:orientation="vertical"
    android:padding="@dimen/component_padding"
    android:layout_height="match_parent" >
</TextView>

</LinearLayout>

一个片段:          

<TextView
    android:text="@string/hello_world"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</TextView>

</LinearLayout>

Logcat说:

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.melle.androidfragments/com.example.melle.androidfragments.MainActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup

 Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup

2 个答案:

答案 0 :(得分:1)

0MQ表示可以在其中包含其他视图的视图。您将单独打开和关闭TextView,并在不能的情况下将它们组成一个组。

根据您发布的代码,解决方案是删除所有Viewgroup并使用</TextView>直接在属性的末尾关闭它,例如:

/>

在所有TextView中执行此操作。另外,检查是否有一些<TextView android:id="@+id/simplefragment" android:layout_width="0px" android:layout_weight="2" android:orientation="vertical" android:padding="@dimen/component_padding" android:layout_height="match_parent" /> 标记,其中包含任何其他视图,如果是,那么您应将其删除并放在其他位置。

答案 1 :(得分:0)

我认为你可能已经找到特定的textview的ViewViewById并将其转换为ViewGroup,例如:

  

ViewGroup simpleFragment =(ViewGroup)   findViewById(R.id.simplefragment);

您无法将textview转换为viewGroup,因为它不是ViewGroup,textview是View。

如果查看android文档,textview会扩展View:http://developer.android.com/reference/android/widget/TextView.html

ViewGroups是RelativeLayout或LinearLayouts或FrameLayouts等对象,可以在其中包含多个视图。