如何在Android中将TextView添加到LinearLayout

145

我正在尝试在代码中向我的xml定义的布局中添加TextViews。 我有一个xml文件,在其中定义了许多Views。但是我需要在代码中添加一些视图,因此在xml文件中创建了一个LinearLayout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>

在这个布局中,我想要添加我的 TextView

    View linearLayout =  findViewById(R.id.info);
    //LinearLayout layout = (LinearLayout) findViewById(R.id.info);


    TextView valueTV = new TextView(this);
    valueTV.setText("hallo hallo");
    valueTV.setId(5);
    valueTV.setLayoutParams(new LayoutParams(
            LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT));

    ((LinearLayout) linearLayout).addView(valueTV);

但是我只得到以下错误信息:

: java.lang.ClassCastException: android.widget.TextView

我该如何做?

谢谢你的帮助。 马丁


那个异常是在哪一行出现的?应该是LinearLayout类型转换的问题,你确定linearLayout变量是一个LinearLayout而不是一个TextView吗?另外,你不应该指定id,因为无法保证唯一性。 - Robby Pond
1
你是对的,linearLayout 是一个 TextView,但为什么呢? 我在 xml 文件中将它定义为 LinearLayout... - Martin
1
确保您正在操作上面显示的xml。setContentView(R.layout.your_xml_layout);是否真正加载了正确的xml?您是否有其他使用android:id =“@+id / info”的xml布局,这恰好是一个TextView? - Rodja
这个问题解决了吗?请接受作为答案或发布一个。 - Talha
9个回答

111

尝试使用

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);
...
linearLayout.addView(valueTV);

同时确保你创建的布局参数是LinearLayout.LayoutParams类型...


又出现了一个异常,因为findViewById返回的是TextView。但是为什么呢?我是用LinearLayout的id获取它的……“也要确保你创建的布局参数是LinearLayout.LayoutParams类型的”,这句话是什么意思? - Martin
为什么这会改变任何事情?它所做的只是尽早而不是晚些时候进行转换,这应该具有相同的效果。 - yesennes

77

嘿,我已经检查了你的代码,你的代码没有严重的错误。这是完整的代码:

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>

这是 Stackoverflow.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Stackoverflow extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View linearLayout =  findViewById(R.id.info);
        //LinearLayout layout = (LinearLayout) findViewById(R.id.info);

        TextView valueTV = new TextView(this);
        valueTV.setText("hallo hallo");
        valueTV.setId(5);
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        ((LinearLayout) linearLayout).addView(valueTV);
    }
}

复制这段代码并运行。它完全没有错误。

注意:


如果我想要以下的TextView怎么办: - Si8
1
+1。这个答案比@Ben的好得多,因为它包含了LayoutParams的示例以及TextView的其余属性如何初始化。应该将其标记为答案。 - Subby
如何在按钮点击onClick(View v)中执行操作 - Moeez

23
for(int j=0;j<30;j++) {
    LinearLayout childLayout = new LinearLayout(MainActivity.this);
    LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
    childLayout.setLayoutParams(linearParams);

    TextView mType = new TextView(MainActivity.this);
    TextView mValue = new TextView(MainActivity.this);

    mType.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));
    mValue.setLayoutParams(new TableLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT, 1f));

    mType.setTextSize(17);
    mType.setPadding(5, 3, 0, 3);
    mType.setTypeface(Typeface.DEFAULT_BOLD);
    mType.setGravity(Gravity.LEFT | Gravity.CENTER);

    mValue.setTextSize(16);
    mValue.setPadding(5, 3, 0, 3);
    mValue.setTypeface(null, Typeface.ITALIC);
    mValue.setGravity(Gravity.LEFT | Gravity.CENTER);

    mType.setText("111");
    mValue.setText("111");

    childLayout.addView(mValue, 0);
    childLayout.addView(mType, 0);

    linear.addView(childLayout);
}

必须定义,linear.addView(childLayout);,linear首先作为线性布局。 - Noor Hossain

23
你可以通过以下方式在代码中将 TextView 添加到你的线性布局中:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
TextView txt1 = new TextView(MyClass.this);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);

MyClass.this是什么?我是Android开发的新手;我应该用我的片段类的名称替换"MyClass"吗? - drusepth
1
MyClass.this 是一个上下文,而 TextView 接受一个上下文。 - Mihai Bratulescu
2
仅供澄清:在大多数情况下,MyClass.thisthis是相同的。但是,如果您在嵌套类中并且想要访问“外部”类的实例,则需要指定类的名称。这在为Android事件定义回调时非常常见。 - drigoangelo
我猜有些安卓开发者习惯于在需要的地方放置类名并开始到处使用。此外,MyClass.thisMyClass的一个实例,只有当MyClass实现了Context(例如扩展Activity)时,它才会成为上下文。 - drigoangelo

12

Kotlin 中,您可以按照以下方式添加Textview。

 val textView = TextView(activity).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(0, 20, 0, 0)
                setPadding(10, 10, 0, 10)
            }
            text = "SOME TEXT"
            setBackgroundColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimary))
            setTextColor(ContextCompat.getColor(this@MainActivity, R.color.colorPrimaryDark))
            textSize = 16.0f
            typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
 linearLayoutContainer.addView(textView)

11

您应该使用类似以下代码将TextView动态添加到LinearLayout:

LinearLayout linearLayout = getActivity().findViewById(R.id.infoLayout);

TextView valueTV = new TextView(context);
valueTV.setText("hallo hallo");
valueTV.setId(Integer.parseInt("5"));
valueTV.setLayoutParams(new LinearLayout.LayoutParams(
       LinearLayout.LayoutParams.FILL_PARENT,
       LinearLayout.LayoutParams.WRAP_CONTENT));

linearLayout.addView(valueTV);

getActivity() 方法用于 Fragment 内部,你可以在每个实例内使用 context 或类似的东西。


3
你需要通过布局资源来访问布局,而不是不保证唯一的id资源。资源引用应该像R.layout.my_cool_layout这样,其中你上面的XML布局存储在res/layout/my_cool_layout.xml中。

0
LinearLayout.LayoutParams layoutParams ;
layoutParams= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

-1

这里是异常发生的地方

((LinearLayout) linearLayout).addView(valueTV);

addView 方法需要传入一个类型为 View 的参数,而不是 TextView。因此,需要将 valueTv 对象强制转换为 View 对象。

因此,修正后的代码应该是:

((LinearLayout) linearLayout).addView((TextView)valueTV);

你测试过这个吗? - mrres1
是的,我有。而且它完美地运作!你试过吗? - user3509153

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接