【问题标题】:Change button state according to checkbox selection in recycler view in android根据android回收器视图中的复选框选择更改按钮状态
【发布时间】:2017-02-18 13:48:26
【问题描述】:

我有一个带有适配器类的回收器视图。在单个项目视图中也有一个复选框。在我的布局视图中,它包含一个按钮和上面提到的回收器视图。当我选中视图中的任何复选框时,该按钮应该被激活(将颜色更改为活动状态)。当视图按钮上未选择任何内容时,应变为停用的形式。我怎么可能?有什么例子吗?代码如下

public class PlatformAdapter extends RecyclerView.Adapter<PlatformAdapter.ViewHolder> {

ArrayList<Batch> batches;
ArrayList<CourseSlug> courses;
boolean isInstituteStudent;

public void setBatches(ArrayList<Batch> batches) {
    this.batches = batches;
    notifyDataSetChanged();
}

public void setCourses(ArrayList<CourseSlug> courses) {
    this.courses = courses;
    notifyDataSetChanged();
}

public ArrayList<CourseSlug> getCourses() {
    return courses;
}

public ArrayList<Batch> getBatches() {
    return batches;
}

public void setInstituteStudent(boolean instituteStudent) {
    isInstituteStudent = instituteStudent;
}

public boolean isInstituteStudent() {
    return isInstituteStudent;
}

public PlatformAdapter() {
    courses = new ArrayList<>();
    batches = new ArrayList<>();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_cell_platform_item, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    if (isInstituteStudent) {
        Batch batch = batches.get(position);
        holder.enrolment.setText(batch.getName());
        holder.selectEnrollment.setChecked(batch.isPreselect());
    } else {
        final CourseSlug course = courses.get(position);
        holder.enrolment.setText(course.getName());
        holder.selectEnrollment.setChecked(course.isPreselect());


    }
}

@Override
public int getItemCount() {
    return isInstituteStudent ? batches.size() : courses.size();
}

class ViewHolder extends RecyclerView.ViewHolder {

    TextView enrolment;
    CheckBox selectEnrollment;

    public ViewHolder(final View itemView) {
        super(itemView);
        enrolment = (TextView) itemView.findViewById(R.id.tv_entrollment);
        selectEnrollment = (CheckBox) itemView.findViewById(R.id.cb_select_entrollment);
        selectEnrollment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                int index = getLayoutPosition();
                if(isInstituteStudent) {
                    Batch batch = batches.get(index);
                    batch.setPreselect(b);
                } else {
                    CourseSlug course = courses.get(index);
                    course.setPreselect(b);



                        }
                    }


        });

    }
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}
}

下面给出了我的 Recyclerview 和按钮实现类

public class SelectPlatform extends BaseActivity {

PlatformAdapter adapter;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    initializeViews(
            findViewById(R.id.ll_content_area),
            findViewById(R.id.tv_error),
            findViewById(R.id.pb_loading)
    );

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_platform);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new PlatformAdapter();
    recyclerView.setAdapter(adapter);


private void renderCourses(ArrayList<CourseSlug> courses) {
    getSupportActionBar().setTitle("Select Courses");
    TextView title = (TextView) findViewById(R.id.tv_select_enrollment);
    title.setText("Select your courses");
    adapter.setInstituteStudent(false);
    adapter.setCourses(courses);
}

private void renderInstitute(Institute institute) {
    getSupportActionBar().setTitle("Select Batches");
    TextView title = (TextView) findViewById(R.id.tv_select_enrollment);
    title.setText("Select your batches at " + institute.getName());
    adapter.setInstituteStudent(true);
    adapter.setBatches(institute.getBatches());

    // Save institute name
    SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
    editor.putString("institute_name", institute.getName());
    editor.commit();
}

public void onButtonClick(View view) {
    findViewById(R.id.pb_loading).setVisibility(View.VISIBLE);
    findViewById(R.id.tv_error).setVisibility(View.GONE);
    findViewById(R.id.ll_content_area).setVisibility(View.GONE);
    if(adapter.isInstituteStudent()) {
        ArrayList<Batch> batches = adapter.getBatches();

        ArrayList<Integer> batchIds = new ArrayList<>();
        for(Batch batch: batches) {
            if(batch.isPreselect())
                batchIds.add(batch.getId());
        }
        GeneralApiService.addBatches(this, batchIds);
    } else {
        ArrayList<CourseSlug> courses = adapter.getCourses();
        ArrayList<String> courseSlgus = new ArrayList<>();
        for(CourseSlug course: courses) {
            if(course.isPreselect())
                courseSlgus.add(course.getSlug());
        }
        GeneralApiService.addCourses(this, courseSlgus);
    }
    new SavePlatformNamesTask().execute();
}

【问题讨论】:

  • 按钮在您的 RecycleviewAdapter 中还是与 Recycleview 分开?
  • @MavyaSoni 不是单独的视图

标签: android checkbox android-recyclerview


【解决方案1】:

像这样在适配器类中发送您的 Button 引用。 public void setBatches(ArrayList batches,Button button) 并为所欲为。

【讨论】:

  • 你能解释更多吗?
  • 您在主类和复选框中的按钮位于您的适配器类右侧。
  • 请分享您调用适配器函数以加载recyclerview的代码。
  • 它只是使用布局查看回收站视图。以及回收站视图容器外的一个按钮。应该控制这个按钮。
  • 只需通过适配器类中的 ArrayList 传递您的按钮。
【解决方案2】:

您可以在适配器内设置一个接口,然后在包含要激活的按钮的活动中实现该接口,然后在复选框的单击事件中发送活动回调并执行您想要的任何更改。

例子:

MyAdapter.java

private MyInterface mListener;

public MyAdpater(Context context, MyInterface listener) {
    this.mListener = listener;
}

selectEnrollment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                // make a callback
                mListener.onCheckBoxClick(true);

                int index = getLayoutPosition();
                if(isInstituteStudent) {
                    Batch batch = batches.get(index);
                    batch.setPreselect(b);
                } else {
                    CourseSlug course = courses.get(index);
                    course.setPreselect(b);

                        }
                    }


        });

public interface MyInterface {
    void onCheckBoxClick(boolean isAnyChecked); 
}

MyActivity.java

    public class MyActivity extends Activity implements MyAdapter.MyInterface {
    // other stuff....


    // Pass listener instance when initializing adapter
    MyAdapter adapter = new MyAdapter(MyActivity.this, this);


    @Override
    public void onCheckBoxClick(boolean isAnyChecked) {
        if(isAnyChecked) {
            // Activate button      
        } else {
            // Deactivate button
        }
    }
}

【讨论】:

    【解决方案3】:

    在您的SelectPlatform 中创建一个字段变量并将其设置为0

    private int checkedBoxs = 0;
    

    并且还可以像这样在SelectPlatform 中创建一个公共方法:

    public void updateButtonState(int num){
       checkedBoxs+=num;
       if(checkedBoxs > 0){
         //Activate the BTN
       }else{
         //Deactivate the BTN
       }
    }
    

    并且修改您的适配器调用以包含来自您的 SelectPlatform 的引用

    adapter = new PlatformAdapter(SelectPlatform.this);
    

    另外不要忘记修改适配器以接收该引用,如下所示:

    a) 向适配器添加字段变量:

    private SelectPlatform mThis;
    

    b) 修改构造函数:

    public PlatformAdapter(SelectPlatform activity) {
        courses = new ArrayList<>();
        batches = new ArrayList<>();
        mThis = activity;
    }
    

    最后在您的适配器中添加/修改checkboxonCheckedChanged 并调用updateButtonState,如下所示:

    selectEnrollment.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    if(selectEnrollment.isChecked()) {
                      mThis.updateState(1);
                    } else {
                      mThis.updateState(-1);
                    }
            });
    

    注意:方法不必是公共的,但它必须具有允许适配器访问它的访问修饰符。

    【讨论】:

    • updateState 不能在适配器类中使用。那里不可见
    • 告诉我你怎么称呼它?你需要使用你的上下文参考!
    • 如何使用上下文引用来调用它?
    • @Arjun 你能告诉我你是如何设置适配器的,以便我可以帮助你
    • @Arjun 现在再次检查答案,我已经修改了它
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2014-08-10
    • 2023-03-18
    相关资源
    最近更新 更多