单击按钮时添加线性布局



我想添加一个线性布局,每当单击按钮时,它都包含文本视图和图像视图 并且添加的线性布局也包含在另一个线性布局中 那我应该怎么做

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main_activity_layout);
final container findViewById(R.id.container);
final LayoutInflater inflater = getLayoutInflater();
Button button = findViewbyId(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addView(inflater, container)
}
});
}
private void addView(LayoutInflater inflater, ViewGroup container) {
inflater.inflate(R.layout.imageview_Label_layout, container, true);
}

在这里,您的布局可以膨胀imageview_Label_layout.xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:layout_marginEnd="10dp"/>
<TextView
android:id="@+id/labelView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="@string/app_name"/>
</LinearLayout>

在这里,您的活动main_activity_layout.xml:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>

最新更新