动态设置textview背景颜色

dynamically setting textview background color

我有一个 table 'D' 每行有 4 个文本视图。我已经设置了 onlicklistener 并且它有效。我想要的是用户按下该行的任何文本视图,文本背景变为 ltgray。我将解决是否设置了每个文本视图或整行。 现在只有最后一个文本视图被设置为 ltgray,无论用户按下什么电视。根据代码,我的假设是我可以通过代码中 x 的索引将每台电视设置为一个 onclick 值:但这不起作用。我不能通过 x 访问每个 textViewB 吗?该代码显示了为其他情况设置的 tvB,但这是设置所有文本视图的文本背景的新情况。我不想要行背景。这很容易并且有效。但只有边框显示。我需要的是更改 table 行中所有 4 台电视的文本背景。 提前致谢:

try {
        for(int x=0 ; x<loopCount; x++){
            TableRow.LayoutParams params = new TableRow.LayoutParams(headerCellsWidth[x + 1], LayoutParams.MATCH_PARENT);
            params.setMargins(2, 2, 0, 0);

            Log.d("Loadrunner", "info[x] " + x + "  " + info[x]);
            final TextView textViewB = this.bodyTextView(info[x]);
            textViewB.setTextColor(0xFF000000);
            tableRowForTableD.addView(textViewB, params);
            //*************************************** Clickable cell
            tableRowForTableD.setClickable(true);
            tableRowForTableD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //tableRowForTableD.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
                    textViewB.setBackgroundColor(Color.LTGRAY);
                    Toast.makeText(getContext(), "Item on aisle select/deselect", Toast.LENGTH_SHORT).show();
                }
            });
            tableRowForTableD.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //tableRowForTableD.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
                    Toast.makeText(getContext(), "Item on aisle Edit", Toast.LENGTH_SHORT).show();
                return true;
                }
            });
            //***************************************************************
        }
    }   catch(Exception e){
        e.printStackTrace();
    }

全部用代码完成。没有 xml 或样式。

yourView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.your_color));

yourView.setBackgroundColor(getResources().getColor(R.color.your_color));

yourView.setBackgroundColor(Color.parseColor("#ffffff"));

我相信您想要的在 onClickListener 中。您已经有了视图,只需更改单击的视图。例如:

@Override
public void onClick(View v) {
    ViewGroup row = (ViewGroup) v.getParent(); 
    for (int itemPos = 0; itemPos < row.getChildCount(); itemPos++) { 
        View view = row.getChildAt(itemPos); 
        if (view instanceof TextView) { 
            textView = (TextView) view;
            textView.setBackgroundColor(Color.LTGRAY);
      }
    } 
    Toast.makeText(getContext(), "Item on aisle select/deselect", Toast.LENGTH_SHORT).show();
}