android - Button数组的RecyclerView - 如何更新数据?

标签 android android-recyclerview listadapter

这是我在网站上的第一个问题,我会尽力把它写好。 我有一个 recyclerView,该 Item 是一个按钮数组。 单击按钮会显示一个弹出菜单,允许用户更改按钮的颜色。 我已经设法设置 onClick 方法将更改颜色,但我对如何将所选颜色保存在保存颜色的 ButtonArrayList 中一无所知。

问题是,当按下按钮时,我不知道如何以编程方式理解按下的是哪个按钮、哪个按钮数组。

谢谢!

只是为了演示问题。单击按钮时,如何识别单击了哪个项目的哪个按钮? 1

fragment 代码:

package com.examples.recyclerViewWithButtonArray;

import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.LinkedList;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link Game#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Game extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    protected static int[] mButtonsColors;

    private final LinkedList<ButtonArray> mButtonArrayList = new LinkedList<>();
    RecyclerView mGuessLinesRecyclerView;
    ButtonArrayListAdapter mButtonArrayListAdapter;
    FloatingActionButton mFab;

    // TODO: Rename and change types of parameters

    public Game() {
        // Required empty public constructor
    }

    public static Game newInstance(String param1, String param2) {
        Game fragment = new Game();
        return fragment;
    }

    private void initGameColors(){
        mButtonsColors = new int[4];
        int[] c = getContext().getResources().getIntArray(R.array.buttonColors);
        //asign colors
        for (int i = 0; i < 4; i++) {
            this.mButtonsColors[i] = c[i];
            }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initGameColors();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View vw = inflater.inflate(R.layout.fragment_game, container, false);
        return vw;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mGuessLinesRecyclerView = view.findViewById(R.id.recycler_view);
        mFab = view.findViewById(R.id.fab);
        //initialize recyclerView
        // Create an adapter and supply the data to be displayed.
        mButtonArrayListAdapter = new ButtonArrayListAdapter(getContext(), mButtonArrayList, this);
        // Connect the adapter with the RecyclerView.
        mGuessLinesRecyclerView.setAdapter(mButtonArrayListAdapter);
        // Give the RecyclerView a default layout manager.
        mGuessLinesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        //initializeFAB
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mButtonArrayList.add(new ButtonArray(getContext(),mButtonsColors));
                mGuessLinesRecyclerView.setAdapter(mButtonArrayListAdapter);
            }
        });


        //add first array to the recycler view.
        // Next guess lines will be added when clicking on movableFab
        mButtonArrayList.add(new ButtonArray(getContext(), this.mButtonsColors));
    }
}



ButtonArrayListAdapter的代码:

package com.examples.recyclerViewWithButtonArray;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

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

public class ButtonArrayListAdapter extends RecyclerView.Adapter<ButtonArrayListAdapter.ButtonArrayViewHolder> {
    private final Context mContext;
    private final List<ButtonArray> mData;
    class ButtonArrayViewHolder extends RecyclerView.ViewHolder {
        public ArrayList<Button> mButtons;
        final ButtonArrayListAdapter mAdapter;
        public ButtonArrayViewHolder(@NonNull View itemView, ButtonArrayListAdapter adapter) {
            super(itemView);
            this.mAdapter = adapter;
            mButtons =new ArrayList<>();
            if(4==4)
            {
                //create an array of button for binding
                mButtons.add((Button)itemView.findViewById(R.id.button_Guess1));
                mButtons.add((Button)itemView.findViewById(R.id.button_Guess2));
                mButtons.add((Button)itemView.findViewById(R.id.button_Guess3));
                mButtons.add((Button)itemView.findViewById(R.id.button_Guess4));
            }
        }
    }

    public ButtonArrayListAdapter(Context mContext, List<ButtonArray> mData, Game mGame) {
        this.mContext = mContext;
        this.mData = mData;
    }

    @NonNull
    @Override
    public ButtonArrayViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View layout;
        layout = LayoutInflater.from(mContext).inflate(R.layout.guess_line,parent,false);
        return new ButtonArrayViewHolder(layout,this);
    }

    @Override
    public void onBindViewHolder(@NonNull final ButtonArrayViewHolder buttonArrayViewHolder, final int position) {
        //bind data here
        //initiate each guessLineButton
        for (int i = 0; i < 4; i++) {
            int c = mData.get(position).mAnswerButtonsColors[i];
            final Button bt = buttonArrayViewHolder.mButtons.get(i);
            //set initial button color
            bt.setBackgroundColor(c);
            //set button clik to open color chooser
            bt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int[] chooseColorButtons = new int[4];

                    // inflate the layout of the popup window
                    final View popupView = LayoutInflater.from(mContext).inflate(R.layout.choose_color_popup,null);
                    // create the popup window
                    int width = bt.getWidth();
                    int height = LinearLayout.LayoutParams.WRAP_CONTENT;
                    boolean focusable = true; // lets taps outside the popup also dismiss it
                    final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);

                    // show the popup window
                    // which view you pass in doesn't matter, it is only used for the window tolken
                    int[] loc = new int[]{0,0};
                    bt.getLocationOnScreen(loc);
                    popupWindow.showAtLocation(v, Gravity.TOP|Gravity.LEFT, loc[0], loc[1] + bt.getHeight());
                    // dismiss the popup window when touched
                    popupView.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            popupWindow.dismiss();
                            return true;
                        }
                    });

                    //initiate each color choose button
                    if(chooseColorButtons.length==4) {
                        chooseColorButtons[0] = R.id.buttonColor1;
                        chooseColorButtons[1] = R.id.buttonColor2;
                        chooseColorButtons[2] = R.id.buttonColor3;
                        chooseColorButtons[3] = R.id.buttonColor4;
                    }

                    for (int j = 0; j < 4 ; j++) {
                        Button colbt = (Button)(popupView.findViewById(chooseColorButtons[j]));
                        colbt.setBackgroundColor(Game.mButtonsColors[j]);

                        colbt.setTextColor(Game.mButtonsColors[j]);
                        colbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                bt.setBackgroundColor(((ColorDrawable)(((Button)v).getBackground())).getColor());
//WHAT SHOULD I DO HERE?
                                popupWindow.dismiss();
                            }
                        });
                    }

                }
            });

        }

    }

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

最佳答案

读完你的问题后,我得到的是你想保存每个按钮的颜色,所以下次当该按钮单击时,应该加载相同的颜色,如果是的话,那么你可以考虑这些 tw0 建议

1-如果按钮的数量是静态的并且您没有动态添加它们,那么您可以通过将它们添加到列表中来对每个按钮的颜色进行硬编码,然后针对每个按钮手动分配它们。

2-您可以使用键值对( HashMap ),这些是任何情况下的最佳解决方案,无论您是手动添加按钮还是动态地仅存储每个键的颜色。在这种情况下,按钮应该是您的键,颜色将是值。

感谢

关于android - Button数组的RecyclerView - 如何更新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62841894/

相关文章:

java - 为什么我的 ListAdapter 没有显示任何数据?

android - 自定义 ListView 不响应click事件

android - 如何使 apk 安全。防止反编译

java - 如何设置定时器,即使App关闭?

java - 错误: on a null object reference, SavedInstanceState旋转回收器 View

android - ListView 布局高度与 Fragment 中 RecyclerView 内的父级不匹配

android - 无法激活 java 类型 MvxRecyclerView 的 JNI 句柄

android - 在 Android Nexus 5 设备上 react native 开发菜单

java.lang.ClassCastException : android. widget.LinearLayout 无法转换为 android.widget

android - 如何在列表中插入复选框