如何以编程方式配置内部布局



我在xml中定义了一个布局,看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/footer_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- add views here -->            
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app"/>
</LinearLayout>

我正在我的活动中夸大它,但RelativeLayout需要根据应用程序中的数据进行TextViews。我怎么可能扩展它并在其中添加不同的视图?


注意:这与这个问题不同,因为我试图弄清楚如何在不使用类来扩展内部布局的情况下添加我要添加的内容。

您只需在代码中创建文本视图即可。然后将它们添加到您的布局中:

RelativeLayout innerLayout= (RelativeLayout)findViewById(R.id.inner_layout);
TextView textView = new TextView(this);
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(p);
innerLayout.addView(textView);

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/footer_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id=@+id/inner_layout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- add views here -->            
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app"/>
</LinearLayout>

活动

RelativeLayout relativelayout=(RelativeLayout) findViewById(R.id.inner_layout);
relativelayout.addview(//Add view here(one will be allowed));

如果在相对布局使用规则中对视图进行排序。最好使用LinearLayout。

最新更新