0

您好我正在尝试根据我的数据模型动态创建布局。但我这样做有一些问题。我拥有的 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");

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

我只能看到dynamic使用指定属性呈现的 xml 布局!

不知道我在哪里犯了错误。是否有可能实现我在这里所做的事情?提前致谢。

4

2 回答 2

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);

于 2013-02-06T08:35:45.843 回答
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);
于 2013-02-06T08:44:15.957 回答