2012-06-13 42 views
6

我想实现这样的事情。 可扩展列表由特定类别的名称组成,当单击父级时,它会显示该类别中所有子级的列表。 现在,假设我想动态地将孩子添加到任何类别? 我该怎么做? 我是否与列表中的每个父母保持一个按钮,点击哪个按钮将添加一个新的孩子?Android ExpandableListView父按钮

但是,在不同的论坛环顾四周,我开始意识到在每个家长中设置一个按钮点击处理程序并不容易。但是,如果这是唯一的方法,请任何人给我一些示例代码吗?

我发现这个线程,但无法在我的代码中实现它。 Android Row becomes Unclickable with Button

+0

你是如何填充列表?从光标?用数组? – Barak

+0

我正在使用数组。 – Swayam

回答

6

将按钮添加到组视图不应该那么困难。

我相信下面应该工作(虽然我没有一个项目使用数组支持ExpandableListView来测试)。

我不知道你的团队行布局,所以我将在这里做一个参考。

group_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/test" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" > 
    <TextView 
     android:id="@android:id/text1" 
     android:layout_width="wrap_content" 
     android:layout_height="35dp" 
     android:focusable="false" 
     android:focusableInTouchMode="false" 
     android:gravity="center_vertical" 
     android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 
    <Button 
     android:id="@+id/addbutton" 
     android:layout_width="wrap_content" 
     android:layout_height="35dp" 
     android:focusable="false" 
     android:focusableInTouchMode="false" 
     android:text="Add" 
     android:textSize="12dp" /> 
</LinearLayout> 

然后从你的适配器的getGroupView方法:

public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { 
    if (convertView == null) { 
     View convertView = View.inflate(getApplicationContext(), R.layout.group_layout, null); 
     Button addButton = (Button)convertView.findViewById(R.id.addButton); 

     addButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       // your code to add to the child list 
      } 
     }); 
    }   
    TextView textView = (TextView)convertView.findViewById(R.id.text1); 
    textView.setText(getGroup(groupPosition).toString()); 
    return convertView; 
}