2014-08-29 97 views
0

我想以编程方式将线性布局项添加到按钮单击上的父网格布局。以编程方式将线性布局项添加到网格布局

所以我第一次点击,网格布局应该是这样的:

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

上发布您的点击收听 – 2014-08-29 06:38:51

+0

代码的最后部分是onclickListener – faizal 2014-08-29 06:40:08

+1

当最后一个参数为真时,检查inflater.inflate返回的内容 – pskink 2014-08-29 06:44:54

回答

2

相反附着到它在充气法根的项目,我手动添加它的父。 即

使用false作为第三个参数来inflate()

View v = inflater.inflate(R.layout.item_reminder, gridLayout, false); 

,并在结尾处使用addView()

gridLayout.addView(v); 
相关问题