当我滚动ListView时,所有带有checked-Items的复选框都未选中

时间:2017-06-19 11:04:07

标签: android listview checkbox android-recyclerview android-arrayadapter

当我使用所选复选框滚动listView时,当我向后滚动时,它们将被取消选中。我知道这是因为Recycler View,但我不知道如何处理复选框状态。请帮助我解决这个问题。我通过看到不同的教程和视频来尽我所能,但却得不到我需要的东西。我是android开发的新手。所有代码都在下面。请帮助我。

Category.java

/**
 * Created by Ali on 14-06-2017.
 */

public class Category {

    private String categoryName;
    private int imageResourceId;
    private boolean isChecked;

    public Category(String categoryName, int imageResourceId)
    {
        this.categoryName = categoryName;
        this.imageResourceId = imageResourceId;
    }

    public Category(String categoryName, int imageResourceId, boolean isCheck)
    {
        this.categoryName = categoryName;
        this.imageResourceId = imageResourceId;
        this.isChecked = isCheck;
    }

    public void setCategoryName(String categoryName)
    {
        this.categoryName = categoryName;
    }
    public String getCategoryName()
    {
        return categoryName;
    }

    public void setImageResourceId(int imageResourceId)
    {
        this.imageResourceId = imageResourceId;
    }

    public int getImageResourceId()
    {
        return imageResourceId;
    }
    public boolean getIsChecked()
    {
        return this.isChecked;
    }
    public void setIsChecked(boolean value)
    {
        this.isChecked = value;
    }
}

CategoryAdapter.java

import android.app.Activity;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ali on 14-06-2017.
 */

public class CategoryAdapter extends ArrayAdapter<Category> {

    private int imageResourceId;

    public CategoryAdapter(Activity context, ArrayList<Category> categories, int newImageResourceId) {

        super(context, 0, categories);


        imageResourceId = newImageResourceId;
    }

    public CategoryAdapter(CategoryActivityScreen activityScreen, ArrayList<Category> categories) {
        super(activityScreen, 0, categories);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view

        View listItemView = convertView;
        if (listItemView == null) {

            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);

        }

        //Below code is before the extra code is written

        // Get the {@link AndroidFlavor} object located at this position in the list
        Category currentCategory = getItem(position);
        ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);

        imageView.setImageResource(currentCategory.getImageResourceId());
        imageView.setVisibility(View.VISIBLE);

        TextView categoryTextView = (TextView) listItemView.findViewById(R.id.categoryNames);
        // Get the version name from the current AndroidFlavor object and
        // set this text on the name TextView
        categoryTextView.setText(currentCategory.getCategoryName());


        CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.checkbox);
        //checkBox.setChecked(false);

        checkBox.setChecked(currentCategory.getIsChecked());


        return listItemView;

    }


}

CategoryActivityScreen.java

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ali on 14-06-2017.
 */

public class CategoryActivityScreen extends AppCompatActivity {


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

        //Currently dummy list is populated
        // Create a list of categories


        final ArrayList<Category> categories = new ArrayList<Category>();
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));
        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Theater", R.drawable.theater_icon, false));
        categories.add(new Category("Places", R.drawable.place_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));

        categories.add(new Category("Food", R.drawable.food_icon, false));
        categories.add(new Category("Games", R.drawable.game_icon, false));


        // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
        // adapter knows how to create list items for each item in the list.

        final CategoryAdapter adapter = new CategoryAdapter(this, categories);


        // Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
        // There should be a {@link ListView} with the view ID called list, which is declared in the
        // word_list.xml layout file.
        ListView listView = (ListView) findViewById(R.id.list);


        //Code for adding footer to listView where list ends. Show's button at the end for next screen
        //---Strats here-----
        LayoutInflater inflater = getLayoutInflater();
        ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer_categories_button, listView, false);
        listView.addFooterView(footer, null, true);
        //---Ends here------

        // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
        // {@link ListView} will display list items for each {@link Word} in the list.

        //// listView.setAdapter(adapter);

    }


}

category_list.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal"
    android:minHeight="60dp">


    <ImageView
        android:layout_width="88dp"
        android:layout_height="88dp"
        android:id="@+id/image" />

    <LinearLayout
        android:id="@+id/text_container"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:orientation="vertical"
        android:paddingLeft="16dp"
        android:layout_toRightOf="@+id/image">

        <TextView
            android:id="@+id/categoryNames"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            tools:text="Food"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="#000000"
            android:textStyle="bold"
            android:gravity="center" />



    </LinearLayout>

    <CheckBox
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="16dp"
        android:id="@+id/checkbox"
        />

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

CategoryAdapter

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /* Some need code here */ 

    CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.checkbox);
    checkBox.setChecked(currentCategory.getIsChecked());
    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

           @Override
           public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
                if(isChecked){
                    currentCategory.setIsChecked(true)
                }else{
                    currentCategory.setIsChecked(false)
                }
           }
       }
    );
    return listItemView;
}

答案 1 :(得分:0)

经过长时间的长时间搜索后,我找到了关于vogella的答案。这些人很棒。如果我说我搜索了很多教程,我没有错。最后,沃格拉终于帮助了我。

CategoryAdapter.java

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CategoryAdapter extends ArrayAdapter<Category> {

    private final ArrayList<Category> list;
    private final Activity context;

    public CategoryAdapter(Activity context, ArrayList<Category> list) {
        super(context, R.layout.list_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected ImageView imageView;
        protected TextView text;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.list_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.imageView = (ImageView) view.findViewById(R.id.image);
            viewHolder.text = (TextView) view.findViewById(R.id.categoryNames);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.checkbox);
            viewHolder.checkbox
                    .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                                     boolean isChecked) {
                            Category element = (Category) viewHolder.checkbox
                                    .getTag();
                            element.setIsChecked(buttonView.isChecked());

                        }
                    });
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.imageView.setImageResource(list.get(position).getImageResourceId());
        holder.text.setText(list.get(position).getCategoryName());
        holder.checkbox.setChecked(list.get(position).getIsChecked());
        return view;
    }
}