我想在按钮单击时以编程方式将线性布局项添加到父网格布局。
因此,首次点击时,网格布局应如下所示:
TextView Button
第二次:
TextView Button TextView Button
第三次:
TextView Button TextView Button TextView Button
但实际发生的是:
第一次:
TextView Button
第二次:
TextView Button Button
第三次:
TextView Button Button Button
即。将更新现有文本视图值,并且每次都会添加一个新按钮。我做错了什么?
这是父布局 - fragment_add.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.GridLayout
xmlns:grid="http://schemas.android.com/apk/res-auto"
android:id="@+id/grdl_reminders"
android:layout_width="match_parent"
android:layout_height="wrap_content"
grid:columnCount="5" />
</ScrollView>
这是项目布局 - item_reminder.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<TextView
android:id="@+id/txt_reminder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2" />
<Button
android:id="@+id/btn_cancelreminder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="0dp"
android:minWidth="0dp"
android:background="@null"
android:text="X"
android:layout_weight="1"
/>
</LinearLayout>
在我的片段中,我在按钮点击时将项目布局膨胀到网格布局中。这是在onCLickListener:
GridLayout gridLayout = (GridLayout) getActivity().findViewById(R.id.grdl_reminders);
//create new item layout
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.item_reminder, gridLayout, true);
TextView tv_reminder = (TextView) v.findViewById(R.id.txt_reminder);
Button btn_cancelReminder = (Button) v.findViewById(R.id.btn_cancelreminder);
String selectedTime = "some new value";
tv_reminder.setText(selectedTime);
答案 0 :(得分:2)
不是在inflate方法中将项目附加到它的根目录,而是手动将其添加到父级。 即。
使用false
作为inflate()
的第三个参数:
View v = inflater.inflate(R.layout.item_reminder, gridLayout, false);
并在最后使用addView()
:
gridLayout.addView(v);