【问题标题】:how to get id of check boxes in expanded list view item?如何在展开的列表视图项中获取复选框的 ID?
【发布时间】:2012-04-11 07:46:49
【问题描述】:

我有一个扩展的列表视图,在父节点和子项中都有复选框。 所有数据都来自网络服务,因此它是动态的。

附上图片:

现在在菜单项上单击我想获取所有复选框状态。 请指导我如何获取其中使用的复选框的 ID。

附上代码:

/**
 * 
 */


    public class Object_SecurityActivity extends ExpandableListActivity {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            // TODO Auto-generated method stub
            return super.onChildClick(parent, v, groupPosition, childPosition, id);
        }

        @Override
        public void onContentChanged() {
            // TODO Auto-generated method stub
            super.onContentChanged();
        }

        private AndroidClientEntity obj_android_client;
        private static final String LOG_TAG = "ElistCBox2";
        private String username, password, clientname;

        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            //setContentView(R.layout.main);
            Intent security_intent = getIntent();
            String id = security_intent.getStringExtra("id");
            obj_android_client = (AndroidClientEntity) getApplicationContext();
            username = obj_android_client.getUsername();
            password = obj_android_client.getPassword();
            clientname = obj_android_client.getClientName();
            new Securityasync().execute(username, password, clientname, id);

        }

        class Securityasync extends AsyncTask<String, String, String> {
            String sesurity_response = null;
            ProgressDialog dialog;
            private Expandable_list_Adapter expListAdapter;

            @Override
            protected String doInBackground(String... params) {
                if ((isOnline(Object_SecurityActivity.this).equals("true"))) {
                    Security_service security_obj = new Security_service();
                    try {
                        sesurity_response = security_obj.getUsersRoles(params[0],
                                params[1], params[2], params[3]);
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                if (isOnline(Object_SecurityActivity.this).equals("true")) {

                    setContentView(R.layout.layout_expandable_listview);
                    ArrayList<String> groupNames = new ArrayList<String>();
                    ArrayList<String> sub = new ArrayList<String>();
                    ArrayList<ArrayList<String>> child = new ArrayList<ArrayList<String>>();
                    ArrayList<String> sub_id = new ArrayList<String>();
                    ArrayList<String> objrid = new ArrayList<String>();
                    try {
                        JSONArray json = new JSONArray(sesurity_response);
                        // JSONArray json_child=new JSONArray(sesurity_response);
                        for (int i = 0; i < json.length(); i++) {
                            JSONObject json_obj = json.getJSONObject(i);
                            if (json_obj.getString("PRid").equalsIgnoreCase("0")) {

                                String ObjectRid = json_obj.getString("ObjectRid");
                                int m=0;
                                objrid.add(m,ObjectRid);
                                m++;
                                groupNames.add(json_obj.getString("Name"));
                                for (int j = 0; j < json.length(); j++) {

                                    JSONObject json_child = json.getJSONObject(j);
                                    if (ObjectRid.equalsIgnoreCase(json_child
                                            .getString("PRid"))) {
                                        int n=0;
                                        sub_id.add(n,json_child.getString("ObjectRid"));
                                        sub.add(json_child.getString("Name"));
                                    }

                                }
                                child.add(sub);

                            }

                        }
                        expListAdapter = new Expandable_list_Adapter(getBaseContext(),
                                groupNames, child);
                        setListAdapter(expListAdapter);
                        Log.e("size in error", "son " + json.length());
                    } catch (JSONException e) {
                        Log.e("", "", e);
                        Toast.makeText(getBaseContext(), "parsing error",
                                Toast.LENGTH_LONG).show();
                    }
                    Log.e("sizeof list", ""+sub_id.size());
                    Iterator itr=objrid.iterator();


                    while(itr.hasNext()){
                        Log.e("id","value "+itr.next());
                    }

                }
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

            }
        }

    }

以及适配器类:

public class Expandable_list_Adapter extends BaseExpandableListAdapter implements OnCheckedChangeListener {

    private Context context;
    private ArrayList<String> groupNames;
    private ArrayList<ArrayList<String>> child;
    private LayoutInflater inflater;

    public Expandable_list_Adapter(Context context, 
                        ArrayList<String> groupNames,
                        ArrayList<ArrayList<String>> child ) { 
        this.context = context;
        this.groupNames= groupNames;
        this.child = child;
        inflater = LayoutInflater.from( context );
    }

    public Object getChild(int groupPosition, int childPosition) {
        return child.get( groupPosition ).get( childPosition );
    }

    public long getChildId(int groupPosition, int childPosition) {
        return (long)( groupPosition*1024+childPosition );  // Max 1024 children per group
    }

    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View v = null;
        if( convertView != null )
            v = convertView;
        else
            v = inflater.inflate(R.layout.child_row, parent, false); 
       String c = (String)getChild( groupPosition, childPosition );
        TextView color = (TextView)v.findViewById( R.id.childname );
        if( color != null )
            color.setText( c );

        CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );

        //cb.setChecked(false);
        cb.setOnCheckedChangeListener(this);
        return v;
    }

    public int getChildrenCount(int groupPosition) {
        return child.get( groupPosition ).size();
    }

    public Object getGroup(int groupPosition) {
        return groupNames.get( groupPosition );        
    }

    public int getGroupCount(){
         return groupNames.size();
    }
    public long getGroupId(int groupPosition) {
        return (long)( groupPosition*1024 );  // To be consistent with getChildId
    } 

    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View v = null;
        if( convertView != null )
            v = convertView;
        else
            v = inflater.inflate(R.layout.group_row, parent, false); 
        String gt = (String)getGroup( groupPosition );
        TextView colorGroup = (TextView)v.findViewById( R.id.childname );
        if( gt != null )
            colorGroup.setText( gt );
        CheckBox cb = (CheckBox)v.findViewById( R.id.check2 );
        cb.setChecked(false);
        return v;
    }

    public boolean hasStableIds() {
        return true;
    }

    public boolean isChildSelectable(int groupPosition, int childPosition) {
        Log.e("is group checked","group "+groupPosition);
        Log.e("selectable","has" +childPosition);
        return true;
    } 

    public void onGroupCollapsed (int groupPosition) {}
    public void onGroupExpanded(int groupPosition) {}

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub

    }
public void isChecked(){

}

}

子.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
      android:background="#21415A"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:id="@+id/childname"
         android:paddingLeft="50px"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="italic"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>

    <TextView android:id="@+id/rgb"
         android:focusable="false"
         android:textSize="14px"
         android:textStyle="italic"
         android:layout_width="100px"
         android:layout_height="wrap_content"/>

    <CheckBox
        android:id="@+id/check1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:focusable="false" />

</RelativeLayout>

parent.xml 与 child.xml 相同。

请指导我如何获取复选框的 ID,因为在选择的菜单项上我必须对其进行操作基础知识。

编辑:我尝试 setTag() 和 getTag() 。但现在可扩展列表视图显示出奇怪的行为。当我选择一个复选框并展开另一个组时,所有 chekbok 框都设置为默认值。 在这种情况下我必须做什么。我不知道为什么它不保存状态。 我面临与Strange behaviour in Expandablelistview - Android相同的问题 请指导

【问题讨论】:

    标签: android checkbox


    【解决方案1】:

    实际上,您在运行时复制的列表或网格上添加的任何控件都具有与您在设计时声明的相同的 id

    例如:在你的情况下,这些是 childname,rgb,check1

    所以如果你需要知道哪个复选框是唯一的 您应该使用 for 循环一一进行

    如果你想做某事为什么不这样做

    复选框点击事件

    public void onClickevent(View v)
    {
    private CheckBox ch = (CheckBox) findViewById(v.getId());
        if (ch.IsChecked){
        //do some thing
         }
    }
    

    或者你应该和我一起去 方式添加一个独特的字段,如

     <TextView
            android:id="@+id/txtComp1_ID"
            android:layout_width="0sp"
            android:layout_height="40sp"
            android:textSize="1pt" >
        </TextView>
    

    因为它的宽度为零,所以它不可见,但它拥有该行的 id

    现在为列表视图中的所有项目运行 for 循环

    findview 你复选框,然后找到它的父项,然后再找到它的子项(文本视图),这个 id 字段 所以现在你有 id 和复选框检查状态,就像以前一样 这样你就可以得到这个

    查看示例

    v = (LinearLayout) findViewById(R.id.LinearNotebookList);
                TextView _id, ID, Name;
                for (int i = 0; i < nCount; i++) {
                    v = (LinearLayout) NotebookList.getAdapter().getView(i, null,
                            null);
                    _id = (TextView) v.findViewById(R.id.txt_Notebook_ID);
    
                    Available = (CheckBox) v
                            .findViewById(R.id.chkboxNotebookAvailable);
                    Display = (CheckBox) v.findViewById(R.id.chkboxNotebookDisplay);
                    Demo = (CheckBox) v.findViewById(R.id.chkboxNotebookDemo);
                    str_id = (String) _id.getText();
    
                    if (Available.isChecked()) {
                        strAvailable = "YES";
                    } else {
                        strAvailable = "NO";
                    }
                    if (Display.isChecked()) {
                        strDisplay = "YES";
                    } else {
                        strDisplay = "NO";
                    }
                    if (Demo.isChecked()) {
                        strDemo = "YES";
                        } else {
                            strDemo = "NO";
                        }
    }
    

    您可以根据需要更改它

    【讨论】:

    • 我试过你的方法。但我只得到一个我在 xml 中定义的 id。但我必须在菜单项选择上获取复选框值。问题是我在哪里以及如何获得所有复选框参考。
    • 是的,我告诉过你,我的应用程序运行良好,您将始终获得唯一的一个 ID,解决此问题的最佳方法告诉我您在此处应用的方法,我会尽我所能解决它
    【解决方案2】:

    只需使用 setTag(int) 和 getTag() 方法来设置 id 和获取控件的 id。比如EditText、复选框等

    【讨论】:

      【解决方案3】:

      使用

      cb.setId(groupPosition+childPosition);
      

      设置 ID 并检索使用:

      cb.getId();
      

      组位置+子位置将为您提供项目的确切位置。

      在 onClick 中,您可以获取您在创建复选框时设置的 ID。

      【讨论】:

      • 我应该在哪里添加:cb.setId(groupPosition+childPosition);
      • 在创建复选框“CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );”之后
      • 好的,但如果组 id 为 1,子 id id 2,组 id 为 2,子 1 在这些情况下,这将是一个冲突
      • 是的。但无论如何,你为什么不采用一个保存相应值的数组,比如 grp1 有 3 个元素, grp 2 有 4 个元素。所以你把它们从 1 编号到 7
      • 其实我不知道有多少团体,有多少孩子。因为所有数据都是动态的。
      【解决方案4】:

      终于解决了我的问题。 适配器类:

       public class Expandable_list_Adapter extends BaseExpandableListAdapter implements OnCheckedChangeListener {
      
          private Context context;
          private ArrayList<String> groupNames;
          private ArrayList<ArrayList<String>> child;
          private LayoutInflater inflater;
      
          public Expandable_list_Adapter(Context context, 
                              ArrayList<String> groupNames,
                              ArrayList<ArrayList<String>> child ) { 
              AndroidClientEntity.objHasmap.clear();
              this.context = context;
              this.groupNames= groupNames;
              this.child = child;
              inflater = LayoutInflater.from( context );
          }
      
          public Object getChild(int groupPosition, int childPosition) {
              return child.get( groupPosition ).get( childPosition );
          }
      
          public long getChildId(int groupPosition, int childPosition) {
              return (long)( groupPosition*1024+childPosition );  // Max 1024 children per group
          }
      
          public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
              View v = null;
              if( convertView != null )
                  v = convertView;
              else
                   v = inflater.inflate(R.layout.child_row, parent, false); 
             String c = (String)getChild( groupPosition, childPosition );
             Log.e("hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii",c);
      
              TextView label = (TextView)v.findViewById( R.id.childname );
              if( label != null )
                  label.setText( c );
      
              CheckBox cb = (CheckBox)v.findViewById( R.id.check1);
              //cb.setId(childPosition);
              cb.setTag(groupPosition+"child"+childPosition);
              cb.setChecked(false);
              if(AndroidClientEntity.objHasmap.get(groupPosition+"child"+childPosition)!=null)
              {
              cb.setChecked(AndroidClientEntity.objHasmap.get(groupPosition+"child"+childPosition));
              }
          //    cb.setOnCheckedChangeListener(this);
              return v;
          }
      
          public int getChildrenCount(int groupPosition) {
              return child.get( groupPosition ).size();
          }
      
          public Object getGroup(int groupPosition) {
      
              return groupNames.get( groupPosition );        
          }
      
          public int getGroupCount(){
               return groupNames.size();
          }
          public long getGroupId(int groupPosition) {
              return (long)( groupPosition*1024 );  // To be consistent with getChildId
          } 
      
          public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
              View v = null;
              if( convertView != null )
                  v = convertView;
              else
                  v = inflater.inflate(R.layout.group_row, parent, false); 
              String gt = (String)getGroup( groupPosition );
              TextView colorGroup = (TextView)v.findViewById( R.id.childname );
              if( gt != null )
                  colorGroup.setText( gt );
              CheckBox cb = (CheckBox)v.findViewById( R.id.check2 );
              cb.setTag(groupPosition+"cbgroup");
              //Object_SecurityActivityobjHasmap.put(groupPosition+"cbgroup", false);
              cb.setChecked(false);
              return v;
          }
      
          public boolean hasStableIds() {
              return true;
          }
      
          public boolean isChildSelectable(int groupPosition, int childPosition) {
              Log.e("is group checked","group "+groupPosition);
              Log.e("selectable","has" +childPosition);
              return true;
          } 
      
          public void onGroupCollapsed (int groupPosition) {}
          public void onGroupExpanded(int groupPosition) {}
      
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              // TODO Auto-generated method stub
      
      
      
          }
      public void isChecked(){
      
      }
      
      }
      

      还有Activity类:

      public class Object_SecurityActivity extends ExpandableListActivity implements OnClickListener{
      
      @Override
      public boolean onChildClick(ExpandableListView parent, View v,
              int groupPosition, int childPosition, long id) {
          // TODO Auto-generated method stub
          CheckBox cb=(CheckBox) v.findViewWithTag(groupPosition+"child"+childPosition);
      //Boolean state=objHasmap.get(groupPosition+"child"+childPosition);
          cb.toggle();
          if(cb.isChecked())
          {
              AndroidClientEntity.objHasmap.put(groupPosition+"child"+childPosition,true );
      
          }else
          {AndroidClientEntity.objHasmap.remove(groupPosition+"child"+childPosition);
      
          }
      
          //add value in set
      //cb.setEnabled(state);
          return super.onChildClick(parent, v, groupPosition, childPosition, id);
      }
      
      
      
      private AndroidClientEntity obj_android_client;
      private static final String LOG_TAG = "ElistCBox2";
      private String username, password, clientname;
      
      @Override
      public void onCreate(Bundle icicle) {
          super.onCreate(icicle);
          //setContentView(R.layout.main);
          Intent security_intent = getIntent();
          String id = security_intent.getStringExtra("id");
      
          obj_android_client = (AndroidClientEntity) getApplicationContext();
          username = obj_android_client.getUsername();
          password = obj_android_client.getPassword();
          clientname = obj_android_client.getClientName();
          new Securityasync().execute(username, password, clientname, id);
      
      }
      
      public boolean onCreateOptionsMenu(Menu menu) {
          new MenuInflater(getApplication()).inflate(R.menu.context_menu_security,
                  menu);
          return (super.onPrepareOptionsMenu(menu));
      }
      public boolean onOptionsItemSelected(MenuItem item) {
          // startDownload();
          if (item.getItemId() == R.id.setsecurity) {
              //code here 
              Log.e("hiiiiiiiiiiiiiiii","scejkkl yu menu pressed");
               }
          return (super.onOptionsItemSelected(item));
      }
      class Securityasync extends AsyncTask<String, String, String> {
          String sesurity_response = null;
          ProgressDialog dialog;
          private Expandable_list_Adapter expListAdapter;
      
          @Override
          protected String doInBackground(String... params) {
              if ((isOnline(Object_SecurityActivity.this).equals("true"))) {
                  Security_service security_obj = new Security_service();
                  try {
                      sesurity_response = security_obj.getUsersRoles(params[0],
                              params[1], params[2], params[3]);
                  } catch (IllegalStateException e) {
                      e.printStackTrace();
                  } catch (JSONException e) {
                      e.printStackTrace();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              return null;
          }
      
          @Override
          protected void onPostExecute(String result) {
              if (isOnline(Object_SecurityActivity.this).equals("true")) {
      
                  setContentView(R.layout.layout_expandable_listview);
                  ArrayList<String> groupNames = new ArrayList<String>();
                  ArrayList<String> sub = new ArrayList<String>();
                  ArrayList<ArrayList<String>> child = new ArrayList<ArrayList<String>>();
                  ArrayList<String> sub_id = new ArrayList<String>();
                  ArrayList<String> objrid = new ArrayList<String>();
                  try {
                      JSONArray json = new JSONArray(sesurity_response);
                      // JSONArray json_child=new JSONArray(sesurity_response);
                      for (int i = 0; i < json.length(); i++) {
                          JSONObject json_obj = json.getJSONObject(i);
                          if (json_obj.getString("PRid").equalsIgnoreCase("0")) {
      
                              String ObjectRid = json_obj.getString("ObjectRid");
                              int m=0;
                              objrid.add(m,ObjectRid);
                              m++;
                              groupNames.add(json_obj.getString("Name"));
                              for (int j = 0; j < json.length(); j++) {
                                  JSONObject json_child = json.getJSONObject(j);
                                  if (ObjectRid.equalsIgnoreCase(json_child
                                          .getString("PRid"))) {
                                      int n=0;
                                      sub_id.add(n,json_child.getString("ObjectRid"));
                                      sub.add(json_child.getString("Name"));
                                  }
      
                              }
                              child.add(sub);
      
                          }
      
                      }
                      expListAdapter = new Expandable_list_Adapter(getBaseContext(),
                              groupNames, child);
                      setListAdapter(expListAdapter);
                      Log.e("size in error", "son " + json.length());
                  } catch (JSONException e) {
                      Log.e("", "", e);
                      Toast.makeText(getBaseContext(), "parsing error",
                              Toast.LENGTH_LONG).show();
                  }
                  Log.e("sizeof list", ""+sub_id.size());
                  Iterator itr=objrid.iterator();
      
      
                  while(itr.hasNext()){
                      Log.e("id","value "+itr.next());
                  }
      
              }
          }
      
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
      
          }
      }
      public void onClick(View v) {
          // TODO Auto-generated method stub
      
      }
      

      }

      感谢 pallavi、amit rai 和 Photon。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2014-09-03
        • 2012-05-03
        • 1970-01-01
        相关资源
        最近更新 更多