选中Listview项时检查复选框

时间:2016-04-08 02:30:32

标签: android listview android-arrayadapter android-checkbox

基本上我有一个listview,其中包含一个处理listview格式化的自定义适配器。适配器使用的自定义视图包含一个复选框,我希望在选中listview项时检查锁定检查。经过多次搜索和各种尝试,我没有成功。任何关于如何实现这一点的想法将不胜感激。

以下是我的主要课程的代码:

public class AbWorkout extends Activity {

Button back;
ListView workoutExerciseList;
WorkoutTracker tracker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ab_workout);


    /**
     * The database used to pull all exercises for this workout routine
     */
    final DatabaseHandler db = new DatabaseHandler(this);
    final SQLiteDatabase database = db.getReadableDatabase();

    final Context context = this;

    /**
     * Get all exercises from Triceps and Chest workout and put in arraylist
     */
    workoutExerciseList = (ListView)findViewById(R.id.listView10);
    final List<String> arrayWorkoutExercises = new ArrayList<String>();
    final ArrayAdapter<String> exListAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, arrayWorkoutExercises);
    workoutExerciseList.setAdapter(exListAdapter);


            //Holds all the available exercises
    final List<WorkoutTracker> exerciseList = db.getRepetitionWorkoutRoutine(context, database, "Abs");

    /**
     * Populates the listView with each exercise for this workout routine. This includes the
     * each exercise name, the number of repetitions, the weight of the exercise, and any
     * comments included.
     */
    List<AbWorkout.RepListViewItem> repProgressList = new ArrayList<>();
    for(int i = 0; i<exerciseList.size(); i++) {
        final int j = i;
        repProgressList.add(new AbWorkout.RepListViewItem()
        {{
                REPETITIONS = exerciseList.get(j).getReps();
                WEIGHT = exerciseList.get(j).getWeight();
                COMMENT = exerciseList.get(j).getComment();
                EXERCISE_NAME = exerciseList.get(j).getExerciseName();
            }});


    }
    final AbViewAdapter adapter = new AbViewAdapter(this, repProgressList);
    workoutExerciseList.setAdapter(adapter);


    CheckBox checkBox = (CheckBox)findViewById(R.id.CheckBox);

    workoutExerciseList.setItemChecked(ListView.CHOICE_MODE_MULTIPLE, true);

    /*
        Upon selection of an exercise, it is highlighted and its name, date,
        and number of reps is stored in repetition progress table
    */
    workoutExerciseList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {

            CheckBox check = (CheckBox) findViewById(R.id.CheckBox);
            //check.setChecked(true);

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
            //Get today's date formatted like this: dd-MM-yy
            String exDate = format.format(calendar.getTime());


            //When exercise is selected, change the color and make it unselectable.
            myAdapter.getChildAt(myItemInt).setBackgroundColor(Color.MAGENTA);
            myAdapter.getChildAt(myItemInt).setEnabled(false);
            myAdapter.getChildAt(myItemInt).setClickable(false);
            myView.setClickable(true);


            tracker = exerciseList.get(myItemInt);
            db.addNewRepProgress(new WorkoutTracker(tracker.getExerciseName(), tracker.getReps(), tracker.getWeight(), tracker.getComment(), exDate), context, database);
            Toast.makeText(context.getApplicationContext(), "Workout Progress was successfully saved.", Toast.LENGTH_LONG).show();

        }
    });


    back = (Button)findViewById(R.id.back);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_ab_workout, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public class RepListViewItem
{
    public int REPETITIONS;
    public double WEIGHT;
    public String COMMENT;
    public String EXERCISE_NAME;
    public String DATE;
}
}

这是我的适配器类的代码:

public class AbViewAdapter extends BaseAdapter
{

LayoutInflater inflater;
List<AbWorkout.RepListViewItem> items;
int pos = 0;

public AbViewAdapter(Activity context, List<AbWorkout.RepListViewItem> items) {
    super();

    this.items = items;
    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return items.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub

    AbWorkout.RepListViewItem item = items.get(position);
    View vi=convertView;

    if(convertView==null)
        vi = inflater.inflate(R.layout.rep_item_row, null);


    TextView exerciseName = (TextView)vi.findViewById(R.id.FullProgress);
    TextView exerciseReps = (TextView)vi.findViewById(R.id.Time);
    TextView exerciseComment = (TextView)vi.findViewById(R.id.Comment);
    TextView exerciseWeight = (TextView)vi.findViewById(R.id.Distance);
    CheckBox check = (CheckBox)vi.findViewById(R.id.CheckBox);

    exerciseName.setText(item.EXERCISE_NAME);
    exerciseReps.setText(String.valueOf(item.REPETITIONS));
    exerciseComment.setText(item.COMMENT);
    exerciseWeight.setText(String.valueOf(item.WEIGHT));

    pos = position;

    return vi;
}
}

2 个答案:

答案 0 :(得分:0)

AbViewAdapter.getView()中,添加OnClickListener

然后,在OnClickListener中,切换复选框状态: check.setChecked(!isChecked())

在此完整答案:Android listview with check boxes?

完整教程:http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html

答案 1 :(得分:0)

因为滚动列表视图时,A中的项目将被销毁。向上滚动时,将重新创建A中的项目。

enter image description here

因此CheckBox也会重新创建,您需要存储项目何时在向上滚动时恢复当前状态。让我们看看ViewHolder