单击列表视图中的所有复选框

时间:2018-02-04 23:43:26

标签: java android

我有一个listview,其中每个listview项都有一个复选框,用户可以选择一个项目。我还有一个checkbox高于listview,预计会在点击时自动检查列表中的所有复选框。 我在实现适当的问题时遇到了问题。有什么想法吗?

public class NotesActivity extends AppCompatActivity {
    private CheckBox universalCheckBox;
    private ListView mListNotes;
    NoteListAdapter na;
    private boolean isAnyItemChecked = false;
   private CheckBox mCheckBox;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notes);
        mListNotes = findViewById(R.id.main_listview);
        // handling long click for list view item
         mListNotes.setLongClickable(true);
        mListNotes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                for (int index = 0; index < parent.getChildCount(); ++index) {
                    View nextChild = (parent.getChildAt(index));
                     mCheckBox = nextChild.findViewById(R.id.checkbox);
                    mCheckBox.setVisibility(View.VISIBLE);
                    universalCheckBox.setVisibility(View.VISIBLE);
                }
                CheckBox checkBox = view.findViewById(R.id.checkbox);
                checkBox.setChecked(true);
                isAnyItemChecked = true;
                return true;
            }
        });
        universalCheckBoxLogic();
    }

    private void universalCheckBoxLogic() {
        universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
             mCheckBox.setChecked(true); // this not working for me

            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

universalCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       @Override
       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {         
                        checkAll(isChecked);

       }
   }
);   

     private void checkAll(boolean checked){
               for (int index = 0; index < parent.getChildCount(); ++index) {
                    View nextChild = (listView.getChildAt(index));
                     mCheckBox = nextChild.findViewById(R.id.checkbox);
                    mCheckBox.setVisibility(View.VISIBLE);
                    mCheckBox.setChecked(checked);
                }

    }