如何在运行时更改widget的text属性,android?

时间:2013-02-06 07:00:30

标签: android android-layout

您好我正在尝试根据我的数据模型动态创建布局。但我这样做有些问题。我的xml文件在这里:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="#f9f9ff">
    <TextView
            android:layout_width="97dp"
            android:layout_height="33dp"
            android:id="@+id/textView" android:layout_alignParentLeft="true" android:layout_marginLeft="15dp"
            android:layout_alignParentTop="true" android:layout_marginTop="19dp"/>
</RelativeLayout>

这被命名为dynamic.xml。我试图在运行时膨胀这个布局。为此我正在做:

    ViewGroup parent = (ViewGroup) findViewById(R.id.vertical_container); 

    //getting the TextView and EditText view.         
    LayoutInflater inflater = this.getLayoutInflater();
    View currentView = inflater.inflate(R.layout.dynamic,null);
    TextView textView = (TextView) currentView.findViewById(R.id.textView);

    //trying to change the attributes. but #fails!
    textView.setText("Setting the text from code");
    textView.setId(3);

    //setting to the view
    view = LayoutInflater.from(getBaseContext()).inflate(R.layout.dynamic, null);
    parent.addView(view);

但这似乎不起作用!这一行:

textView.setText("Setting the text from code");

不起作用。我只能在模拟器中看到空文本,但看不到文本Setting the text from code。不确定我在哪里弄错了。我在代码中所做的更改在我的模拟器中看不到。

我只能看到呈现其属性的dynamic xml布局!

不知道我在哪里弄错了。有可能实现我在这里做的事情吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您目前正在添加

view = LayoutInflater.from(getBaseContext()).inflate(R.layout.dynamic, null);parent.addView(view);

但你使用textView.setText("Setting the text from code"); 由此 View currentView = inflater.inflate(R.layout.dynamic,null);

您没有将currentView添加到parent

试试这个parent.addView(currentView);

答案 1 :(得分:1)

我认为你为获得结果设置了错误的观点。不需要两次布局膨胀

//getting the TextView and EditText view.         
LayoutInflater inflater = this.getLayoutInflater();
View currentView = inflater.inflate(R.layout.dynamic,null);
TextView textView = (TextView) currentView.findViewById(R.id.textView);

//trying to change the attributes. but #fails!
textView.setText("Setting the text from code");
textView.setId(3);

//Now you had customize your Textview .Now just add this customize view to your view
//setting to the view
parent.addView(currentView);