首页 > 解决方案 > 如何设置动态创建的Textview的背景颜色?

问题描述

我在 android 中创建动态文本视图。视图已创建,但是当我单击 textview 时,我想在 android 中设置该特定 textview 的背景颜色。我已经尝试过,但它将颜色设置为仅最后一个文本视图而不是选定的文本视图。

这是我的代码

public class Demo extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout llOptions;
    private TextView textView, tvOptionFirstQue;
    private ArrayList<String> arrayList = new ArrayList<>();
    private static final int MY_BUTTON = 9000;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_quiz_demo);
        llOptions = findViewById(R.id.llOptions);
        tvOptionFirstQue = findViewById(R.id.tvOptionFirstQue);

        for (int i = 0; i < 4; i++) {
            textView = new TextView(Demo
                    .this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            float left = getResources().getDimension(R.dimen.common_twentyfive);
            float top = getResources().getDimension(R.dimen.common_five);
            float toppadding = getResources().getDimension(R.dimen.common_twelve);
            float right = getResources().getDimension(R.dimen.common_twentyfive);
            params.setMargins((int) left, (int) top, (int) right, 0);
            textView.setPadding(0, (int) toppadding, 0, (int) toppadding);
            textView.setTextSize(14);
            textView.setBackgroundResource(R.drawable.button_background_light_gray);
            textView.setGravity(Gravity.CENTER);
            textView.setTextColor(Color.BLACK);
            textView.setId(i);
            textView.setLayoutParams(params);
            textView.setText("test" + i);
            textView.setOnClickListener(this);
            arrayList.add(textView.getText().toString());
            this.llOptions.addView(textView);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case 0:
                View child = llOptions.getChildAt(v.getId());
                TextView textView1 = (TextView) child;
                onFirstOptionClisk(textView1);


        }
    }

    private void onFirstOptionClisk(TextView textView) {
        textView.setBackgroundResource(R.drawable.rounded_lightblue_answer_backgroun);
        textView.setTextColor(getResources().getColor(R.color.white));
    }

标签: androidtextview

解决方案


利用

textView.setBackgroundColor(Color.parseColor("#00ff00"));

反而

textView.setBackgroundResource(R.drawable.button_background_light_gray)

将工作


推荐阅读