如何在 Android 中将 TextView 添加到 LinearLayout [英] How to add a TextView to LinearLayout in Android

查看:35
本文介绍了如何在 Android 中将 TextView 添加到 LinearLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 TextViews 添加到我的 xml 定义的代码布局中.我有一个 xml 表,其中定义了很多 Views.但是我必须在代码中添加一些视图,因此在 xml-sheet 中创建一个 LinearLayout:

I am trying to add TextViews to my xml-defined layout in code. I have a xml-sheet, where a lot of Views are defined. But I have to add some views in code, so a create a LinearLayout in the xml-sheet:

<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:

And in this layout, I like to add my 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);

但我只收到以下错误消息:

But I only get the following error message:

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

我该怎么做?

谢谢你的帮助.马丁

推荐答案

尝试使用

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

还要确保您创建的布局参数是 LinearLayout.LayoutParams...

also make sure that the layout params you're creating are LinearLayout.LayoutParams...

这篇关于如何在 Android 中将 TextView 添加到 LinearLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆