带有自定义选择器的Android复选框,在recyclerview中

时间:2016-04-10 12:56:36

标签: java android xml checkbox android-recyclerview

我使用复选框制作了recyclerview,这样当你按下列表中的选定项目时,你可以选择屏幕底部的每个项目和按钮。问题是无论我做什么按钮总是返回0项被选中。我发现复选框状态始终为false,即使我单击复选框时复选框中的图标也会更改。我使用自定义选择器更改复选框内的图标,但我无法找到更改程序内复选框状态的方法。

这是包含recyclerview

的片段
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    Resources res = getResources();
    titles = res.getStringArray(R.array.muscle_titles);

    recyclerMain = (RecyclerView) rootView.findViewById(R.id.MainList);
    adapter = new MainAdapter(getActivity(), getData(getActivity()));
    recyclerMain.setAdapter(adapter);
    recyclerMain.setLayoutManager(new LinearLayoutManager(getActivity()));
    return rootView;
}

public static List<MainRowInformation> getData(Context context){
    List<MainRowInformation> data = new ArrayList<>();


    for(int i=0;i<titles.length;i++){

        final MainRowInformation current = new MainRowInformation();
        current.title = titles[i];
        current.checkBox = new CheckBox(context);
        current.checkBox.setChecked(false);


        data.add(current);
    }

    return data;
}

这是recyclerview适配器

    private LayoutInflater inflater;
private List<MainRowInformation> data = Collections.emptyList();

public MainAdapter(Context context, List<MainRowInformation> data) {
    this.data = data;
    inflater = LayoutInflater.from(context);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_main, parent, false);
    MyViewHolder holder = new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    MainRowInformation current = data.get(position);
    holder.title.setText(current.title);
    //mozda je krivo sljedeca linija
    holder.checkbox = current.checkBox;

}

@Override
public int getItemCount() {
    return data.size();
}

class MyViewHolder extends RecyclerView.ViewHolder{

    TextView title;
    CheckBox checkbox;

    public MyViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.MainListText);
        checkbox = (CheckBox) itemView.findViewById(R.id.MainListCheckBox);

    }
}

复选框

    <CheckBox
    android:id="@+id/MainListCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/main_list_button_icon"/>

复选框选择器

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/ic_list_uncheck"
    android:state_checked="false" />
<item android:drawable="@mipmap/ic_list_check"
    android:state_checked="true"/>

the button return 0 but 3 items were selected

0 个答案:

没有答案