以编程方式设置按钮颜色

时间:2017-03-15 07:28:13

标签: android button background android-recyclerview android-cardview

我正在设置按钮背景颜色。我的按钮是从数组值生成的,并使用recyclerview和cardview创建布局。一切正常,单击按钮设置了精美的颜色。当我点击第一个按钮'D'时它会设置背景但是会自动设置为按钮'M'而不是单击并继续按下按钮单击'E'同样自动将背景设置为按钮'N',依此类推。它在第9个位置按钮M,N,O ........

之后自动将颜色设置为按钮

这是我的片段类。

    public class Cart_fragment extends Fragment {
    public static ImageView img1,img2,img3,img4,img5,img6,img7,img8,img9,img10;
    public static String [] colorarray={"D","E","F","G","H","I","J","K","L","M","N","O-P","Q-R","S-T","U-V","W-X","Y-Z"};
    public static String [] clarity={"IF","FL","VVS1","VVS2","VS1","VS2","SI1","SI2","SI3","I1","I2","I3"};
    public static String [] cut={"IDL","EX","VG","GD","FR","PR"};
    public static String [] polish={"EX","VG","GD","FR","PR","POLISH"};
    public static String [] symmetry={"EX","VG","GD","FR","PR","SYMM"};
    public static String [] fluorance={"NON","VSLT","SLT","FNT","MED","STG"};
    public static String [] lab={"GIA","IGI","HRD","OWN","EGL"};
    public static String [] location={"MUMBAI","MUMBAI1","MUMBAI2","SURAT"};
    public static String [] Intensity={"DEEP","FAINT","FANCY","FANCY DARK","FANCY DEEP","FANCY VIVID","FANCY INTENSE",
            "FANCY LIGHT","LIGHT","VERYLIGHT"};
    public static String [] overtone={"YELLOWISH","BROWNISH","BROWNISH GREEN","BLUISH","GRAYISH","GRAYISH YELLOWISH","GRAYISH GREENISH",
            "GREENISH","PINKISH","PURPLISH"};
    public static String [] colorfancy={"BROWN","YELLOW","GREEN","PINK","GRAY","BLUE","GREEN YELLOW","ORANGE BROWN","YELLOW GREEN"};
    RadioGroup radg;
    RadioButton white,fancy;
    String flag="true";
    String flag2="false";
    String flag3="normal";
    View rootView;
    int counter=0;
    Recyleradapter adapter;
    LinearLayout fancyshow,whitehide;
    RecyclerView recyclerView, clarityrecylerview,cutrecyler,polishrecyler,symmetryrecyler,fluorancerecyler,
            labrecylerlab,loc_recyler,intensityrecylerview,overtonerecylerview,fancycolorrecylerview;
    List<String> colorlist;

      public static Cart_fragment newInstance() {
        Cart_fragment fragment = new Cart_fragment();
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.cartfrag, container, false);

        img1=(ImageView)rootView.findViewById(R.id.img1);
        img2=(ImageView)rootView.findViewById(R.id.img2);
        img3=(ImageView)rootView.findViewById(R.id.img3);
        img4=(ImageView)rootView.findViewById(R.id.img4);
        img5=(ImageView)rootView.findViewById(R.id.img5);
        img6=(ImageView)rootView.findViewById(R.id.img6);
        img7=(ImageView)rootView.findViewById(R.id.img7);
        img8=(ImageView)rootView.findViewById(R.id.img8);
        img9=(ImageView)rootView.findViewById(R.id.img9);
        img10=(ImageView)rootView.findViewById(R.id.img10);
        radg=(RadioGroup)rootView.findViewById(R.id.radgrp);
        white=(RadioButton)rootView.findViewById(R.id.white);
        fancy=(RadioButton)rootView.findViewById(R.id.fancyradio);
        fancyshow=(LinearLayout)rootView.findViewById(R.id.fancy);
        whitehide=(LinearLayout)rootView.findViewById(R.id.whitecolorhide);


        img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img1);
            }
        });
        img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img2);
            }
        });
        img3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img3);
            }
        });
        img4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img4);
            }
        });
        img5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img5);
            }
        });
        img6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img6);
            }
        });
        img7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img7);
            }
        });
        img8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img8);
            }
        });
        img9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img9);
            }
        });
        img10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addbackcolor(img10);
            }
        });

        recyclerView = (RecyclerView)rootView.findViewById(R.id.color_recyler);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(horizontalLayoutManagaer);

        clarityrecylerview = (RecyclerView)rootView.findViewById(R.id.clarity_recyler);
        clarityrecylerview.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer1 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        clarityrecylerview.setLayoutManager(horizontalLayoutManagaer1);

        cutrecyler = (RecyclerView)rootView.findViewById(R.id.cut_recyler);
        cutrecyler.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer2 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        cutrecyler.setLayoutManager(horizontalLayoutManagaer2);

        polishrecyler = (RecyclerView)rootView.findViewById(R.id.polish_recyler);
        polishrecyler.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer3 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        polishrecyler.setLayoutManager(horizontalLayoutManagaer3);

        symmetryrecyler = (RecyclerView)rootView.findViewById(R.id.symmetry_recyler);
        symmetryrecyler.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer4 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        symmetryrecyler.setLayoutManager(horizontalLayoutManagaer4);

        fluorancerecyler = (RecyclerView)rootView.findViewById(R.id.fluorance_recyler);
        fluorancerecyler.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer5 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        fluorancerecyler.setLayoutManager(horizontalLayoutManagaer5);

        labrecylerlab = (RecyclerView)rootView.findViewById(R.id.lab_recyler);
        labrecylerlab.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer6 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        labrecylerlab.setLayoutManager(horizontalLayoutManagaer6);

        loc_recyler = (RecyclerView)rootView.findViewById(R.id.loc_recyler);
        loc_recyler.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer7 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        loc_recyler.setLayoutManager(horizontalLayoutManagaer7);

        intensityrecylerview = (RecyclerView)rootView.findViewById(R.id.intensity_recyler);
        intensityrecylerview.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer8 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        intensityrecylerview.setLayoutManager(horizontalLayoutManagaer8);

        overtonerecylerview = (RecyclerView)rootView.findViewById(R.id.overtone_recyler);
        overtonerecylerview.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer9 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        overtonerecylerview.setLayoutManager(horizontalLayoutManagaer9);

        fancycolorrecylerview = (RecyclerView)rootView.findViewById(R.id.colorfancy_recyler);
        fancycolorrecylerview.setHasFixedSize(true);
        LinearLayoutManager horizontalLayoutManagaer10 = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        fancycolorrecylerview.setLayoutManager(horizontalLayoutManagaer10);

        addarray(colorarray);
        addarray(clarity);
        addarray(cut);
        addarray(polish);
        addarray(symmetry);
        addarray(fluorance);
        addarray(lab);
        addarray(location);
        addarray(Intensity);
        addarray(overtone);
        addarray(colorfancy);
        white.setChecked(true);
        white.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                whitehide.setVisibility(View.VISIBLE);
                fancyshow.setVisibility(View.GONE);
            }
        });
        fancy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                whitehide.setVisibility(View.GONE);
                fancyshow.setVisibility(View.VISIBLE);
            }
        });

        return rootView;
    }

    private void addbackcolor(ImageView img1) {
        img1.setBackgroundResource(R.drawable.roundedbackground);
    }

    private void addarray(String[] colorarray) {
        colorlist = new ArrayList<>();
        for (int i = 0; i < colorarray.length; i++) {
            colorlist.add(colorarray[i]);
        }
        addadapter(colorlist);
    }

    private void addadapter(List<String> colorlist) {
        if(counter==7){
            adapter = new Recyleradapter(getContext(),(ArrayList<String>) colorlist,flag);
        }else if(counter==8||counter==9||counter==10){
            adapter = new Recyleradapter(getContext(),(ArrayList<String>) colorlist,flag2);
        }else {
            adapter = new Recyleradapter(getContext(),(ArrayList<String>) colorlist,flag3);
        }

        counter++;
        addrecyler(adapter,counter);
    }

    private void addrecyler(Recyleradapter adapter, int counter) {
        int getcount=counter;
        if(getcount==1){
            recyclerView.setAdapter(adapter);
        }else if (getcount==2){
            clarityrecylerview.setAdapter(adapter);
        }else if (getcount==3){
            cutrecyler.setAdapter(adapter);
        }else if (getcount==4){
            polishrecyler.setAdapter(adapter);
        }else if (getcount==5){
            symmetryrecyler.setAdapter(adapter);
        }else if (getcount==6){
            fluorancerecyler.setAdapter(adapter);
        }else if (getcount==7){
            labrecylerlab.setAdapter(adapter);
        }else if (getcount==8){
            loc_recyler.setAdapter(adapter);
        }else if (getcount==9){
            intensityrecylerview.setAdapter(adapter);
        }else if (getcount==10){
            overtonerecylerview.setAdapter(adapter);
        }else if (getcount==11){
            fancycolorrecylerview.setAdapter(adapter);
        }
    }
}

这里是适配器类,我根据数组的大小和设置背景颜色创建按钮。

适配器类

public class Recyleradapter extends RecyclerView.Adapter<Recyleradapter.Viewholder> {
    Context ctx;
    String flag,colorstring;
    int counter = 0,counter2 = 0;

    View view;
    String [] buttonid = {"btnpex","btnpvg","btnpgd","btnpfr","btnppr",""};
    String [] buttonsymm={"btnsex","btnsvg","btnsgd","btnsfr","btnspr",""};
    StringBuffer result2color=new StringBuffer();
    StringBuffer getResult2clarity=new StringBuffer();
    StringBuffer getResult2cut=new StringBuffer();
    StringBuffer getResult2polish=new StringBuffer();
    StringBuffer getResult2symmetry=new StringBuffer();
    StringBuffer getResult2fluorance=new StringBuffer();
    StringBuffer getResult2lab=new StringBuffer();
    StringBuffer getResult2loca=new StringBuffer();
    StringBuffer getResult2intensity=new StringBuffer();
    StringBuffer getResult2overtone=new StringBuffer();
    StringBuffer getResult2colorfancy=new StringBuffer();

    private ArrayList<String> countries;

    public Recyleradapter(Context context, ArrayList<String> countries, String flag) {
        this.ctx=context;
        this.flag=flag;
        this.countries = countries;
    }

    @Override
    public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(flag.equals("true")){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_listview1, parent, false);
        }else if (flag.equals("false")){
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_listview2, parent, false);
        }else{
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_listview, parent, false);
        }
        return new Viewholder(view);
    }

    @Override
    public void onBindViewHolder(final Viewholder holder, final int position) {
        final int    size = countries.size()-1;
        if(countries.contains("POLISH")){
            holder.tv_country.setTag(buttonid[position]);
        }
        if(countries.contains("SYMM")){
            holder.tv_country.setTag(buttonsymm[position]);
        }
        if ( countries.contains("POLISH") || countries.contains("SYMM")) {
            holder.tv_country.setText(countries.get(position));

            if (position == size) {
                countries.remove(position);
            }
        } else {
            holder.tv_country.setText(countries.get(position));
        }
        holder.tv_country.setOnClickListener(new View.OnClickListener() {
            final String str = holder.tv_country.getText().toString().trim();

            @Override
            public void onClick(View v) {

                if (holder.tv_country.getTag()!=null){
                        if (holder.tv_country.getTag().equals("btnpex")) {
                            getResult2polish.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnpvg")){
                            getResult2polish.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnpgd")){
                            getResult2polish.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnpfr")){
                            getResult2polish.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnppr")){
                            getResult2polish.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                        if (holder.tv_country.getTag().equals("btnsex")) {
                            getResult2symmetry.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnsvg")) {
                            getResult2symmetry.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnsgd")) {
                            getResult2symmetry.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnsfr")) {
                            getResult2symmetry.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }else if (holder.tv_country.getTag().equals("btnspr")) {
                            getResult2symmetry.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                }
                    for (int i = 0; i < Cart_fragment.colorarray.length; i++) {
                        if (Cart_fragment.colorarray[i].equals(str.toString().trim())) {
                            addbackccolor(holder.tv_country);
                            result2color.append(str + ",");
                            Log.e("iii", String.valueOf(i));
                        }
                    }
                    for (int i = 0; i < Cart_fragment.clarity.length; i++) {
                        if (Cart_fragment.clarity[i].equals(str.toString().trim())) {
                            getResult2clarity.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }

                    for (int i = 0; i < Cart_fragment.cut.length; i++) {
                        if (countries.get(0).equals("IDL") && Cart_fragment.cut[i].equals(str.toString().trim())) {
                            getResult2cut.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }

                    for (int i = 0; i < Cart_fragment.fluorance.length; i++) {
                        if (Cart_fragment.fluorance[i].equals(str.toString().trim())) {
                            getResult2fluorance.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }
                    for (int i = 0; i < Cart_fragment.lab.length; i++) {
                        if (Cart_fragment.lab[i].equals(str.toString().trim())) {
                            getResult2lab.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }
                    for (int i = 0; i < Cart_fragment.location.length; i++) {
                        if (Cart_fragment.location[i].equals(str.toString().trim())) {
                            getResult2loca.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }
                    for (int i = 0; i < Cart_fragment.Intensity.length; i++) {
                        if (Cart_fragment.Intensity[i].equals(str.toString().trim())) {
                            getResult2intensity.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }
                    for (int i = 0; i < Cart_fragment.overtone.length; i++) {
                        if (Cart_fragment.overtone[i].equals(str.toString().trim())) {
                            getResult2overtone.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }
                    for (int i = 0; i < Cart_fragment.colorfancy.length; i++) {
                        if (Cart_fragment.colorfancy[i].equals(str.toString().trim())) {
                            getResult2colorfancy.append(str + ",");
                            addbackccolor(holder.tv_country);
                        }
                    }

                Log.e("position", String.valueOf(position));
//                Log.e("countrer", String.valueOf(counter));
                Log.e("countrer2", String.valueOf(counter2));
                Log.e("whitecolor", result2color.toString());
                Log.e("clarity", getResult2clarity.toString());
                Log.e("cut", getResult2cut.toString());
                Log.e("polish", getResult2polish.toString());
                Log.e("symme", getResult2symmetry.toString());
                Log.e("lab", getResult2lab.toString());
                Log.e("locat", getResult2loca.toString());
                Log.e("flaoura", getResult2fluorance.toString());
                Log.e("intensity", getResult2intensity.toString());
                Log.e("overtone", getResult2overtone.toString());
                Log.e("fancycolor", getResult2colorfancy.toString());
            }
        });
    }

    private void addbackccolor(Button tv_country) {
        tv_country.setBackgroundResource(R.drawable.roundedbackground);
    }

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

    public class Viewholder extends RecyclerView.ViewHolder {
        private Button tv_country;
        public Viewholder(View itemView) {
            super(itemView);
            tv_country = (Button)itemView.findViewById(R.id.btn);
        }
    }
}

3 个答案:

答案 0 :(得分:2)

你应该添加一个&#34; else&#34;对于每一个&#34;如果&#34; onBindViewHolder方法中的条件会改变您的背景颜色,您应该在其中设置默认的背景颜色。

编辑: 您也应该更改所有循环,例如替换它:

 for (int i = 0; i < Cart_fragment.location.length; i++) {
                    if (Cart_fragment.location[i].equals(str.toString().trim())) {
                        getResult2loca.append(str + ",");
                        addbackccolor(holder.tv_country);
                    }
                }

with:

 for (int i = 0; i < Cart_fragment.location.length; i++) {
                if (Cart_fragment.location[i].equals(str.toString().trim())) {
                    getResult2loca.append(str + ",");
                    addbackccolor(holder.tv_country);
                }
               else
                  setDefaultBackColor(holder.tv_country);
            }

答案 1 :(得分:1)

RecyclerView重复使用(回收)其单元格时,您需要在适配器的onBindViewHolder(...) {..}中再次将颜色设置为默认值(不仅仅是onClick)。然后它应该工作。

<强>更新

同样从@Reza中获取答案,您可以在if语句中添加else块来设置默认颜色,如下所示:

if (holder.tv_country.getTag()!=null){
        if (holder.tv_country.getTag().equals("btnpex")) {
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnpvg")){
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnpgd")){
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnpfr")){
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnppr")){
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
        } else {
            //SET DEFAULT COLOR HERE
        }
        if (holder.tv_country.getTag().equals("btnsex")) {
            getResult2symmetry.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnsvg")) {
            getResult2symmetry.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnsgd")) {
            getResult2symmetry.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnsfr")) {
            getResult2symmetry.append(str + ",");
            addbackccolor(holder.tv_country);
        }else if (holder.tv_country.getTag().equals("btnspr")) {
            getResult2symmetry.append(str + ",");
            addbackccolor(holder.tv_country);
        }
        else {
            //SET DEFAULT COLOR HERE
        }
    }

另一种可能性(仅仅因为我更喜欢切换那些长的if-else,如果块是一个开关:

if (holder.tv_country.getTag()!=null){
        switch (holder.tv_country.getTag()) {
            case "btnpex":
            getResult2polish.append(str + ",");
            addbackccolor(holder.tv_country);
            break;
            //other cases...
            default:
                //SET DEFAULT COLOR HERE
        }
    }

答案 2 :(得分:1)

您可以在数组或列表中保存按钮的状态,并在onViewBind中应用它。使用xml文件根据状态更改颜色。