recyclelerview,单击突出显示并使其他人不突出显示

时间:2016-08-08 12:55:48

标签: android android-recyclerview

我有信用卡的回收视图,如果你点击一个,我希望它改变那个的背景资源,并使所有其他的恢复到默认,由于某种原因,我已经打了大约5个小时,不能正确。

这是失败的班级

    public class CheckOutCardRecycler extends RecyclerView.Adapter<CheckOutCardRecycler.CardViewHolder>{

    private List<Card> checkOutCard;
    private int screenWidth;
    private int selected;






    public CheckOutCardRecycler(Activity activity, List<Card> checkOutCard){


        Display display = activity.getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        this.screenWidth = size.x;
        this.checkOutCard = checkOutCard;
        selected=-1;


    }



    public static class CardViewHolder extends RecyclerView.ViewHolder {
         CardView card;
         LinearLayout row;
        static TextView etCardNumber;
        static TextView etName;
        static TextView etDate;
        static LinearLayout creditCard;



        CardViewHolder(View itemView) {
            super(itemView);
            card = (CardView)itemView.findViewById(R.id.card_view);
            etCardNumber = (TextView)itemView.findViewById(R.id.etCardNumber);
            etName = (TextView)itemView.findViewById(R.id.etName);
            etDate = (TextView)itemView.findViewById(R.id.etDate);
            creditCard = (LinearLayout) itemView.findViewById(R.id.creditCard);

        }
    }

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

    public int getSelected() {
        return selected;
    }

    public int getPaymentMethod(int i) {
        return Integer.parseInt(checkOutCard.get(i).getId());
    }


    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_checkout_cards, viewGroup, false);
        CardViewHolder pvh = new CardViewHolder(v);

        return pvh;
    }

    @Override
    public void onBindViewHolder(final CardViewHolder cardViewHolder, final int i) {
        CardViewHolder.etCardNumber.setText("**** **** **** " + checkOutCard.get(i).getLast_four_digits());
        CardViewHolder.etName.setText(checkOutCard.get(i).getName());
        CardViewHolder.etDate.setText(checkOutCard.get(i).getExpiry_month() +"/"+checkOutCard.get(i).getExpiry_year().substring(2,4));
        if (selected<0)
            if (checkOutCard.get(i).getDefaultcard()==1){
                selected=i;
            }

        CardViewHolder.creditCard.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                if (i!=selected) {

                    checkOutCard.get(selected).setDefaultcard(0);
                    checkOutCard.get(i).setDefaultcard(1);
                    selected=-1;

                    notifyDataSetChanged();




                }
            }
        });


        if (selected==i){
            if (checkOutCard.get(i).getBrand().toLowerCase().equals("visa"))
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreenvisaselected);
            else if (checkOutCard.get(i).getBrand().toLowerCase().equals("mastercard"))
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreenmastercardselected);
            else
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreenselected);
        }
        else {

            if (checkOutCard.get(i).getBrand().toLowerCase().equals("visa"))
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreenvisa);
            else if (checkOutCard.get(i).getBrand().toLowerCase().equals("mastercard"))
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreenmastercard);
            else
                CardViewHolder.creditCard.setBackgroundResource(R.drawable.paymentscreen);

        }


    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

    }




}

3 个答案:

答案 0 :(得分:1)

你的适配器应该看起来像这样:

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
    private Context context;
    private List<Card> checkOutCard;
    private int screenWidth; // I really think you shouldn't calculate your width in the adapter but before your create it.
    private Card selected;

    public CardAdapter(Context context, List<Card> checkOutCard, int screenWidth) {
        this.context = context;
        this.screenWidth = screenWidth;
        this.checkOutCard = checkOutCard;
    }

    protected Context getContext() {
        return context;
    }

    protected Card getItem(int position){

    }

    public Card getSelected() {
        return selected;
    }

    public void setSelected(Card selected) {
        this.selected = selected;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new CardViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.row_checkout_cards, parent, false));
    }

    @Override
    public void onBindViewHolder(CardViewHolder holder, int position) {
        Card currentCard = getItem(position);
        holder.bind(currentCard, currentCard == selected);

    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public static class CardViewHolder extends RecyclerView.ViewHolder {
        CardView card;
        LinearLayout row;
        static TextView etCardNumber;
        static TextView etName;
        static TextView etDate;
        static LinearLayout creditCard;

        CardViewHolder(View itemView) {
            super(itemView);
            card = (CardView)itemView.findViewById(R.id.card_view);
            etCardNumber = (TextView)itemView.findViewById(R.id.etCardNumber);
            etName = (TextView)itemView.findViewById(R.id.etName);
            etDate = (TextView)itemView.findViewById(R.id.etDate);
            creditCard = (LinearLayout) itemView.findViewById(R.id.creditCard);

        }

        public void bind(Card card, boolean isSelected){
            etCardNumber.setText("**** **** **** " + card.getLast_four_digits());
            etName.setText(card.getName());
            etDate.setText(card.getExpiry_month() +"/"+card.getExpiry_year().substring(2,4));
            if (isSelected)
                if (card.getDefaultcard()==1){
                    selected=i;
                }

            creditCard.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {

                    if (i!=selected) {

                        checkOutCard.get(selected).setDefaultcard(0);
                        card.setDefaultcard(1);
                        selected=-1;

                        notifyDataSetChanged();




                    }
                }
            });


            if (selected==i){
                if (card.getBrand().toLowerCase().equals("visa"))
                    creditCard.setBackgroundResource(R.drawable.paymentscreenvisaselected);
                else if (card.getBrand().toLowerCase().equals("mastercard"))
                    creditCard.setBackgroundResource(R.drawable.paymentscreenmastercardselected);
                else
                    creditCard.setBackgroundResource(R.drawable.paymentscreenselected);
            }
            else {

                if (card.getBrand().toLowerCase().equals("visa"))
                    creditCard.setBackgroundResource(R.drawable.paymentscreenvisa);
                else if (card.getBrand().toLowerCase().equals("mastercard"))
                    creditCard.setBackgroundResource(R.drawable.paymentscreenmastercard);
                else
                    creditCard.setBackgroundResource(R.drawable.paymentscreen);

            }
        }
    }
}

答案 1 :(得分:1)

这是一个有效的例子:

适配器:

public class TestAdapter extends RecyclerView.Adapter<TestAdapter.TestViewHolder> {


    private List<String> mData;
    Context mContext;
    RecyclerView mRecyclerView;


    public class TestViewHolder extends RecyclerView.ViewHolder{

        LinearLayout mListItemLayout;
        TextView mTextView;
        int mPosition;

        public TestViewHolder(final View itemView) {
            super(itemView);
            mListItemLayout = (LinearLayout) itemView.findViewById(R.id.list_item);
            mTextView = (TextView) itemView.findViewById(R.id.list_item_text);
            mListItemLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemView.setBackgroundColor(Color.RED);
                    grayBackgroundOfOtherItems();
                }
            });

        }

        public void setPosition(int position){
            mPosition = position;
        }

        private void grayBackgroundOfOtherItems(){

            int size = mData.size();
            for(int i=0; i<size; i++){
                if(i != mPosition){
                    TestViewHolder viewHolder = (TestViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i);
                    ((TestViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i)).
                                           mListItemLayout.setBackgroundColor(Color.LTGRAY);
                }
            }
        }

    }

    public TestAdapter(Context context, RecyclerView recyclerView){

        this.mContext = context;
        this.mRecyclerView = recyclerView;
        initData();
    }

    private void initData(){

        mData = new ArrayList<String>();
        mData.add("Africa");
        mData.add("Antartica");
        mData.add("Asia");
        mData.add("Australia");
        mData.add("Europe");
        mData.add("North America");
        mData.add("South America");
    }

    @Override
    public TestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
        TestViewHolder viewHolder = new TestViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(TestViewHolder holder, int position) {

        holder.mTextView.setText(mData.get(position));
        holder.setPosition(position);
    }

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

活动:

public class CardViewActivity extends AppCompatActivity{

    RecyclerView mRecyclerView;


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

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(new TestAdapter(this,mRecyclerView));
    }
}

活动的布局:

<?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="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".stack_overflow_cardview.CardViewActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

每个列表项的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id = "@+id/list_item"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_marginTop="10dp">

    <TextView
        android:id = "@+id/list_item_text"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />

</LinearLayout>

截图:

enter image description here

希望这很有用。

编辑:如果您不熟悉在您的适配器中引用它的ReclerView,您可以使用您的活动/片段必须实现的接口并将该位置传递给接口方法。

答案 2 :(得分:-1)

感谢大家的回答,最后几天尝试了所有的解决方案,但没有一个工作,也没有解决为什么我最终想出来,我有一个愚蠢的语法问题,让我头疼。

我所要做的就是在onBindViewHolder里面我必须将所有的CardViewHolder更改为cardViewHolder。我想这使得这个问题对其他人来说毫无意义,所以我的虔诚和再次感谢所有其他人做出长篇答案的努力