gpt4 book ai didi

android - 将 TextView 添加到 LinearLayout 时出现 ClassCastException

转载 作者:行者123 更新时间:2023-11-29 18:13:04 25 4
gpt4 key购买 nike

我想以编程方式向 LinearLayout 添加一些 TextViews。我想使用 LayoutInflater。我的 Activity 布局 xml 文件中有:

<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
/>

我在下面写了这样的 Activity 代码。

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);

我的 scale.xml 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:drawableTop="@drawable/unit"
/>

在行 TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true); 我有如下致命异常。

 java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}: 
java.lang.ClassCastException: android.widget.LinearLayout
Caused by: java.lang.ClassCastException: android.widget.LinearLayout

当我将有问题的行 linearLayout 替换为 null 时,我没有任何异常,但是 android:layout_marginLeftandroid:layout_marginRight我的 scale.xml 被忽略,我看不到添加的 TextView 周围有任何边距。

我找到了问题 Android: ClassCastException when adding a header view to ExpandableListView但就我而言,我在使用充气机的第一行有异常(exception)。

最佳答案

当您在对 inflater.inflate() 的调用中指定 Root View (linearLayout) 时, inflatedView 会自动添加到 View 层次结构中。因此,您不需要调用 addView。此外,如您所见,返回的 View 是层次结构的 Root View (LinearLayout)。要获取对 TextView 本身的引用,您可以使用以下方法检索它:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.scale, linearLayout, true);
TextView textView = (TextView) linearLayout.getChildAt(
linearLayout.getChildCount()-1);
textView.setText("Some text");

如果您要在 scale.xml 中为 View 提供一个 android:id 属性,您可以使用以下命令检索它

TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);

关于android - 将 TextView 添加到 LinearLayout 时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9658913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com