安卓:添加一个TextView线性布局编程 [英] Android: Add a textview to linear layout programmatically

查看:129
本文介绍了安卓:添加一个TextView线性布局编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想补充 TextViews 在code我的XML定义的布局。 我有一个XML表,那里有很多的浏览定义。但是,我要补充的code的一些看法,所以创建一个的LinearLayout 在XML表:

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

    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

我该怎么办呢?

How can I do it?

感谢您的帮助。 马丁

推荐答案

尝试使用

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

也确保布局PARAMS你创建的LinearLayout.LayoutParams ...

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

这篇关于安卓:添加一个TextView线性布局编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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