2013-02-14 75 views
5

我正在使用expandablelistview。無論如何,我可以在點擊內部圖像時擴展組行。我知道要讓圖片響應點擊,我必須設定其焦點。現在,一旦這個圖像響應點擊(在我的custome適配器內),我如何以編程方式展開/摺疊它所屬的特定組行?在可擴展列表中以編程方式展開組行可以擴展列表

謝謝

回答

11

在適配器

private OnItemSelectedListener onItemSelectedCallback; 

public interface OnItemsSelectedListener { 
    public void onImageSelected(int groupPos); 
} 

public YourAdapter(Context context) { 
    try { 
     this.onItemSelectedCallback = (OnItemSelectedListener) context; 
    } 
    catch (ClassCastException e) { 
     throw new ClassCastException(context.toString() + " must implement OnItemSelectedListener "); 
    } 
} 

在getView()添加這個

ImageView imageView = new ImageView(); 
imageView.setTag(R.id.tagGroupPosition, groupPosition); 
imageView.setOnClickListener(onClickListener); 

在OnClickListener

OnClickListener onClickListener = new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     int groupPos = ((ImageView) v).getTagId(R.id.tagGroupPosition); 
     onItemSelectedCallback.onImageSelected(groupPos); 
    } 
} 

加入這個然後在活動中,你必須工具喲urAdapter.OnItemsSelectedListener的覆蓋onImageSelected

@Override 
public void onImageSelected(int groupPos){ 
    if(expandableList.isGroupExpanded(groupPos)){ 
     expandableList.collapseGroup(groupPos); 
    }else{ 
     expandableList.expandGroup(groupPos); 
    } 
} 
+0

在哪裏崩潰/擴大答案這是我的問題背後的原因? – Snake 2013-02-14 21:20:45

+0

我已添加更多代碼來澄清我的答案,請參閱。希望這可以幫到你。 – Pongpat 2013-02-15 04:58:33

+0

謝謝你的回答。公認 – Snake 2013-02-15 05:26:49

2

更簡單的方法:

  1. 傳遞到適配器構造函數中ExpandableListView參考;
  2. getGroupView在您需要的按鈕添加一個OnClickListener和簡單的調用listView.expandGroup(position);

例子:

public class YourAdapter extends BaseExpandableListAdapter { 

private ExpandableListView listView; 

public ReportsAdapter(ExpandableListView listView) { 
    this.listView = listView; 
} 

//... 

@Override 
public View getGroupView(final int position, boolean isExpanded, View convertView, ViewGroup parent) { 
    ParentViewHolder holder; 

    if (convertView == null) { 
     convertView = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.your_item, parent, false); 

     holder = new ParentViewHolder(); 

     //... holder logic 


     holder.btnExpand = convertView.findViewById(R.id.btn_expand); 

     convertView.setTag(holder); 
    } else { 
     holder = (ParentViewHolder) convertView.getTag(); 
    } 

    //..holder logic 

    holder.btnExpand.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      listView.expandGroup(position); 
     } 
    }); 

    return convertView; 
} 

在您的活動onCreate()或片段onCreateView()

ExpandableListView listView = (ExpandableListView) view.findViewById(R.id.expandable_list_view); 
    mAdapter = new YourAdapter(listView); 
    listView.setAdapter(mAdapter);