当我以编程方式添加背景可绘制时,按钮的文本消失

时间:2017-07-24 22:22:57

标签: android android-layout listview android-adapter

我正在尝试动态创建按钮列表,而不使用ListViewsAdapters

我使用水平布局,然后动态添加按钮。当我向按钮添加背景可绘制时,文本会自动消失。

以下是代码:

        mSizeButtons=new ArrayList<Button>();
        mSizeLayout=(LinearLayout)findViewById(R.id.sneaker_size_activity_lv_size);
        String[] shoeSizes={"2.0","2.5","3.0","3.5","4.0","4.5","5.0","5.5","6.0","6.5","7.0","7.5"      ,"8.0","8.5","9.0","9.5","10.0","10.5","11.0","11.5","12","12.5","13.0","13.5","14.0","14.5","15.0","15.5","16.0"
        ,"16.5","17.0","17.5","18.0"};


        LinearLayout.LayoutParams lprams = new LinearLayout.LayoutParams(
               120,
                120);
        lprams.setMargins(15,0,0,0);

        for(int i=0;i<shoeSizes.length;i++){
            Button btn = new Button(this);
            btn.setLayoutParams(lprams);


            btn.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.sneaker_size_button_white));
            btn.setText(shoeSizes[i]);
           // btn.setTextColor(Color.BLACK);

            btn.setTag(i);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int tag=(int)v.getTag();

                    for(Button btn : mSizeButtons){
                        btn.setBackgroundDrawable(ContextCompat.getDrawable(SneakerSizeActivity.this,
                                R.drawable.sneaker_size_button_white));
                    }
                    mSizeButtons.get(tag).setBackgroundDrawable(ContextCompat.getDrawable(SneakerSizeActivity.this,
                            R.drawable.sneaker_size_button_black));
                    mSizeButtons.get(tag).setTextColor(Color.WHITE);

                }
            });
            mSizeButtons.add(btn);
            mSizeLayout.addView(btn);
        }

1 个答案:

答案 0 :(得分:0)

我认为你的文字并没有消失。当有背景时,你无法看到文字。只需尝试更改背景图片或文字颜色