public void onClick(View arg0) {
x++;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView textOut = (TextView) addView
.findViewById(R.id.textout);
textOut.setText(x + "");
Button buttonRemove = (Button) addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((LinearLayout) addView.getParent())
.removeView(addView);
}
});
container.addView(addView);
}
row.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center" >
<Button
android:id="@+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Remove" />
<TextView
android:id="@+id/textout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/remove" />
</LinearLayout>
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
<LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|clip_vertical"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
在上面的例子中,当我点击button.it工作正常时,我将row.xml扩展为活动主XML。但我需要从下到上填充这些项目。这意味着如果我添加第一个元素,然后下一个元素应该添加到该元素的顶部。在我的方法中,我添加第二个元素id来自1元素