Android的ExpandableListView与复选框,控制选中状态 [英] Android ExpandableListView with Checkbox, Controlling checked state

查看:904
本文介绍了Android的ExpandableListView与复选框,控制选中状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

我试图写它使用复选框ExpandableListView一个应用程序,我在这里是保持应用程序的复选框状态有一个问题,我接到的此处,我的问题是如何保持的复选框的选中状态,每当我检查复选框之一,并展开列表,复选框没有他们应该选中状态有。我曾尝试加入的ArrayList来存储商店的位置,并重新加载getChildView()的位置,但仍没有达到我想要做维护。这里是我的code

 公共类ElistCBox扩展ExpandableListActivity {

    私有静态最后弦乐LOG_TAG =ElistCBox;
    ArrayList的<字符串> chkState =新的ArrayList<字符串>();
    静态最后弦乐的颜色[] = {灰色,蓝,黄,红};
    静态最后字符串的色调[] [] = {{浅灰,#D3D3D3,暗灰,#696969,SGI>灰92,#EAEAEA},
        {宝蓝2,#1C86EE,钢青→2,#5CACEE,浅灰蓝,#B0E0E6},
        {黄色1,#FFFF00,黄金1,#FFD700,深金黄1,#FFB90F},
        {印地安1,#FF6A6A,耐火砖1,#FF3030,栗色,#800000}};

    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包冰柱)
    {
        super.onCreate(冰柱);
        的setContentView(R.layout.main);
        SimpleExpandableListAdapter expListAdapter =新SimpleExpandableListAdapter(
            本,
            createGroupList(),
            R.layout.group_row,新的String [] {colorName},
            新的INT [] {} R.id.childname,createChildList()
            R.layout.child_row,
            新的String [] {shadeName,RGB},
            新的INT [] {R.id.childname,R.id.rgb}
        ){
            @覆盖公共查看getChildView(最终诠释groupPosition,最终诠释childPosition,布尔isLastChild,查看convertView,父母的ViewGroup)
            {
                最终的视图V = super.getChildView(groupPosition,childPosition,isLastChild,convertView,父母);

                最终的复选框chkColor =(复选框)v.findViewById(R.id.check1);

                如果(chkState.contains(groupPosition +,+ childPosition)){
                    chkColor.setChecked(真正的);
                }其他{
                    chkColor.setChecked(假);
                }
                chkColor.setOnClickListener(新OnClickListener(){
                    @覆盖
                    公共无效的onClick(视图v){
                        Log.e(复选框的onclick监听器,Integer.toString(groupPosition)+ - + Integer.toString(childPosition));
                    }
                });
                chkColor.setOnCheckedChangeListener(新OnCheckedChangeListener(){
                    @覆盖
                    公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                        Log.e(复选框选中此选项更改侦听器,Integer.toString(groupPosition)+ - + Integer.toString(childPosition));
                        如果(chkColor.isChecked()){
                            chkState.add(groupPosition +,+ childPosition);
                        } 其他 {
                            chkState.remove(groupPosition +,+ childPosition);
                        }
                    }
                });
                返回super.getChildView(groupPosition,childPosition,isLastChild,convertView,父母);
            }
        };
        setListAdapter(expListAdapter);
    }

    公共无效onContentChanged(){
        super.onContentChanged();
        Log.e(LOG_TAGonContentChanged);
    }

    公共布尔onChildClick(
            ExpandableListView父母,
            视图V,
            INT groupPosition,
            INT childPosition,
            长ID){
        Log.e(LOG_TAGonChildClick:+ childPosition);
        复选框CB =(复选框)v.findViewById(R.id.check1);
        如果(CB!= NULL)
        cb.toggle();
        返回false;
    }

    公共无效onGroupExpand(INT groupPosition){
        Log.e(LOG_TAGonGroupExpand:+ groupPosition);
    }

    私人列表createGroupList(){
        ArrayList的结果=新的ArrayList();
        的for(int i = 0; I< colors.length ++我){
            HashMap的M =新的HashMap();
            m.put(colorName,颜色[I]);
            result.add(米);
        }
        返程(列表)的结果;
    }

    私人列表createChildList(){
        ArrayList的结果=新的ArrayList();
        的for(int i = 0; I< shades.length ++我){
            ArrayList的secList =新的ArrayList();
            对于(INT N = 0; N<色调[I] .length; N + = 2){
                HashMap的孩子=新的HashMap();
                child.put(shadeName,浓淡[I] [n])的;
                child.put(RGB,色调[I] [N + 1]); secList.add(子);
            }
            result.add(secList);
        }
        返回结果;
    }
}
 

解决方案

这就是我的回答对这个问题,ü需要保持状态检查个别孩子,检查它的孩子被点击时。经过一番研究,这是由于Android的观点生命周期导致以刷新因此没有保持状态。

 公共类MyExpandableListAdapter扩展BaseExpandableListAdapter {
//变量
//样本数据集。孩子们[I]包含儿童(字符串[])团体[1]。
私有String []组= {人名称,狗名,名猫,鱼名}; //头
私有String [] []孩子= {
        {阿诺德,巴里,查克,大卫},
        {王牌,强盗,双查,平分},
        {蓬松,的Snuggles},
        {戈尔迪,泡}
};
私有String [] group_vaues = {PN,DN,CN,FN};
私有String [] [] children_values​​ = {
        {AR,巴,CH,大},
        {王牌,封杀,茶,申},
        {流感,的Snu},
        {高尔,布勃}
};
ArrayList的< ArrayList的<整数GT;> check_states =新的ArrayList< ArrayList的<整数GT;>();

私人上下文的背景下;

//构造函数
公共MyExpandableListAdapter(){

}

公共MyExpandableListAdapter(上下文C){
    this.context = C;
}

//设置方法
公共无效setGroupsAndValues​​(字符串[]克的String [] V){
    this.groups =克;
    v this.group_vaues =;
}

公共无效setChildrenAndValues​​(字符串[] [] C,的String [] [] V){
    this.children = C;
    v this.children_values​​ =;
    //初始化状态,以全0;
    的for(int i = 0; I< c.length;我++){
        ArrayList的<整数GT; TMP =新的ArrayList<整数GT;();
        为(诠释J = 0; J&c为C [i]于.length; J ++){
            tmp.add(0);
        }
        check_states.add(TMP);
    }
}

//获取方法
公共对象getChild(INT groupPosition,诠释childPosition){
    返回儿[groupPosition] [childPosition]
}

众长getChildId(INT groupPosition,诠释childPosition){
    返回childPosition;
}

公众诠释getChildrenCount(INT groupPosition){
    返回儿[groupPosition] .length;
}

公共查看getChildView(INT groupPosition,诠释childPosition,布尔isLastChild,
        查看convertView,ViewGroup中父){
    查看网格;


   LayoutInflater充气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   格= inflater.inflate(R.layout.specialty_list_item,父母,假);

   最终诠释grpPos = groupPosition;
   最终诠释childPos = childPosition;

    TextView的头=(TextView中)grid.findViewById(R.id.title);
    header.setText(getChild(groupPosition,childPosition)的ToString());
    最后查看打勾= grid.findViewById(R.id.image);
    如果(check_states.get(grpPos)获得(childPos)== 1)
        tick.setVisibility(View.VISIBLE);
    其他
        tick.setVisibility(View.GONE);

    grid.setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            check_states.get(grpPos).SET(childPos,1);
            tick.setVisibility(View.VISIBLE);
        }
    });

    回电网;
}

公共对象getGroup(INT groupPosition){
    返回组[groupPosition]
}

公众诠释getGroupCount(){
    返回groups.length;
}

众长getGroupId(INT groupPosition){
    返回groupPosition;
}

公共查看getGroupView(INT groupPosition,布尔isExpanded,查看convertView,
        ViewGroup中父){
    查看网格;

    如果(convertView == NULL){
       格=新景(背景);
       LayoutInflater充气=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       格= inflater.inflate(R.layout.specialty_header,父母,假);
    }其他{
       格=(查看)convertView;
    }

    TextView的头=(TextView中)grid.findViewById(R.id.specialty_header);
    header.setText(getGroup(groupPosition)的ToString());


    回电网;
}

公共布尔isChildSelectable(INT groupPosition,诠释childPosition){
    返回true;
}

公共布尔hasStableIds(){
    返回true;
}
 

}

Friends,

I am trying to write a application which use checkbox in ExpandableListView, I got a problem here which is maintaining checkbox state of the application, I got the example from here , my problem is maintaining checked state of the checkboxes, whenever I check one of the checkboxes and Expand the List, the checkboxes do not have the checked state where they supposed to have. I have try to maintain by adding ArrayList to store the position of the store and reload the position in getChildView() but still not achieve what I want to do. here is my code

public class ElistCBox extends ExpandableListActivity {

    private static final String LOG_TAG = "ElistCBox";
    ArrayList<String > chkState = new ArrayList<String>();
    static final String colors[] = {"grey","blue","yellow","red"};
    static final String shades[][] ={ { "lightgrey","#D3D3D3","dimgray","#696969", "sgi >gray 92","#EAEAEA"},
        { "dodgerblue 2","#1C86EE","steelblue >2","#5CACEE","powderblue","#B0E0E6"},
        { "yellow 1","#FFFF00", "gold 1","#FFD700","darkgoldenrod 1"," #FFB90F" },
        {"indianred 1","#FF6A6A", "firebrick 1","#FF3030", "maroon","#800000" } };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle)
    {
        super.onCreate(icicle);
        setContentView(R.layout.main); 
        SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter( 
            this,
            createGroupList(),
            R.layout.group_row, new String[] { "colorName" },
            new int[] { R.id.childname }, createChildList(),
            R.layout.child_row,
            new String[] { "shadeName", "rgb" },
            new int[] { R.id.childname, R.id.rgb }
        ) { 
            @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
            {
                final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);

                final CheckBox chkColor = (CheckBox)v.findViewById(R.id.check1);

                if(chkState.contains(groupPosition+","+childPosition)){
                    chkColor.setChecked(true);
                }else{
                    chkColor.setChecked(false);
                }
                chkColor.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("Checkbox Onclick Listener", Integer.toString(groupPosition) + " - " + Integer.toString(childPosition));
                    }
                });
                chkColor.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        Log.e("Checkbox check change Listener", Integer.toString(groupPosition) + " - " + Integer.toString(childPosition));
                        if(chkColor.isChecked()){
                            chkState.add(groupPosition+","+childPosition);
                        } else {
                            chkState.remove(groupPosition+","+childPosition); 
                        }
                    }
                });
                return super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
            }
        };
        setListAdapter( expListAdapter );
    }

    public void onContentChanged  () {
        super.onContentChanged();
        Log.e( LOG_TAG, "onContentChanged" );
    }

    public boolean onChildClick(
            ExpandableListView parent, 
            View v, 
            int groupPosition,
            int childPosition,
            long id) {
        Log.e( LOG_TAG, "onChildClick: "+childPosition );
        CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
        if( cb != null )
        cb.toggle();
        return false;
    }

    public void  onGroupExpand  (int groupPosition) {
        Log.e( LOG_TAG,"onGroupExpand: "+groupPosition );
    }

    private List createGroupList() {
        ArrayList result = new ArrayList();
        for( int i = 0 ; i < colors.length ; ++i ) {
            HashMap m = new HashMap();
            m.put( "colorName",colors[i] );
            result.add( m );
        }
        return (List)result; 
    }

    private List createChildList() {
        ArrayList result = new ArrayList();
        for( int i = 0 ; i < shades.length ; ++i ) {
            ArrayList secList = new ArrayList();
            for( int n = 0 ; n < shades[i].length; n += 2 ) {
                HashMap child = new HashMap();
                child.put( "shadeName", shades[i][n] );
                child.put( "rgb", shades[i][n+1] ); secList.add( child );
            }
            result.add( secList );
        } 
        return result;
    }
}

解决方案

this is my answer to the this issue, u need to keep a check state for individual child and check on it when the the child is clicked. after some research, this is due to android's view lifecycle causing the view to refresh thus not keeping the state.

public class MyExpandableListAdapter extends BaseExpandableListAdapter {
//Variables
// Sample data set.  children[i] contains the children (String[]) for groups[i].
private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" }; //headers
private String[][] children = {
        { "Arnold", "Barry", "Chuck", "David" },
        { "Ace", "Bandit", "Cha-Cha", "Deuce" },
        { "Fluffy", "Snuggles" },
        { "Goldy", "Bubbles" }
};
private String[] group_vaues = {"PN", "DN", "CN", "FN"};
private String[][] children_values = {
        { "Ar", "Ba", "Ch", "Da" },
        { "Ace", "Ban", "Cha", "Deu" },
        { "Flu", "Snu" },
        { "Gol", "Bub" }
};
ArrayList<ArrayList<Integer>> check_states = new ArrayList<ArrayList<Integer>>();

private Context context;

//Constructors
public MyExpandableListAdapter() {

}

public MyExpandableListAdapter(Context c) {
    this.context = c;
}

//Set Methods
public void setGroupsAndValues(String[] g, String[] v) {
    this.groups = g;
    this.group_vaues = v;
}

public void setChildrenAndValues(String[][] c, String[][] v) {
    this.children = c;
    this.children_values = v;
    //initialize the states to all 0;
    for(int i = 0; i < c.length; i++) {
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        for(int j = 0; j < c[i].length; j++) {
            tmp.add(0);
        }
        check_states.add(tmp);
    }
}

//Get Methods
public Object getChild(int groupPosition, int childPosition) {
    return children[groupPosition][childPosition];
}

public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

public int getChildrenCount(int groupPosition) {
    return children[groupPosition].length;
}

public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
        View convertView, ViewGroup parent) {
    View grid;


   LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   grid = inflater.inflate(R.layout.specialty_list_item, parent, false);

   final int grpPos = groupPosition;
   final int childPos = childPosition;

    TextView header = (TextView)grid.findViewById(R.id.title);
    header.setText(getChild(groupPosition, childPosition).toString());
    final View tick = grid.findViewById(R.id.image);
    if(check_states.get(grpPos).get(childPos) == 1)
        tick.setVisibility(View.VISIBLE);
    else
        tick.setVisibility(View.GONE);

    grid.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v) {
            check_states.get(grpPos).set(childPos, 1);
            tick.setVisibility(View.VISIBLE);
        }
    });

    return grid;
}

public Object getGroup(int groupPosition) {
    return groups[groupPosition];
}

public int getGroupCount() {
    return groups.length;
}

public long getGroupId(int groupPosition) {
    return groupPosition;
}

public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
        ViewGroup parent) {
    View grid;

    if(convertView==null){
       grid = new View(context);
       LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       grid = inflater.inflate(R.layout.specialty_header, parent, false);
    }else{
       grid = (View)convertView;
    }

    TextView header = (TextView)grid.findViewById(R.id.specialty_header);
    header.setText(getGroup(groupPosition).toString());


    return grid;
}

public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

public boolean hasStableIds() {
    return true;
}

}

这篇关于Android的ExpandableListView与复选框,控制选中状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆