list with checkBoxes in a navigation drawer

2019-04-17 09:54发布

Im trying to make a navigation drawer with a listview that has check boxes in it. as each list item. this is what i have tried so far , But im having great difficulty.

what im looking to is create a prefence menu. i.e "bluetooth on/off (checkbox)" etc

Heres My Main Activity:

public class MainActivity extends ActionBarActivity {

//Navigation Drawer Member Variables
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;

//Navigation Drawer

    mDrawerList = (ListView)findViewById(R.id.navList);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    mActivityTitle = getTitle().toString();

    addDrawerItems();
    setupDrawer();

 private void addDrawerItems() {
    String[] osArray = { "Bluetooth", "Reply to Calls", "Reply to sms", "customise message"};
    mAdapter = new ArrayAdapter<String>(this, R.layout.list_item, osArray);
    mDrawerList.setAdapter(mAdapter);

    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            CheckedTextView ctv = (CheckedTextView)view;
            if (ctv.isChecked()){
                Toast.makeText(getApplicationContext(),"uncheckd",Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(),"checked",Toast.LENGTH_LONG).show();
            }

        }
    });
}



    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

Im getting an error saying that the adapter needs a text view. Any help would be greatly appreciated. Thanks

1条回答
霸刀☆藐视天下
2楼-- · 2019-04-17 10:15

The error you are getting is beacuse you have to pass a TextView instead of R.layout.list_item, check the below example:

 mAdapter = new ArrayAdapter<String>(this, R.layout.my_textview, osArray);

To create a ListView with checkboxes set the ChoiceMode to "CHOICE_MODE_MULTIPLE"

    String[] osArray = {"Bluetooth", "Reply to Calls", "Reply to sms", "customise message"};
    ListView listView = (ListView) findViewById(R.id.listView);
    ArrayAdapter arrayAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, osArray);

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    listView.setAdapter(arrayAdapter);

Result: enter image description here

查看更多
登录 后发表回答