我有一个表“D”,每行有 4 个 TextView 。我已经设置了 onlicklistener 并且它有效。我想要的是用户按下该行的任何 TextView ,文本背景变为 ltgray。我将解决是否设置了每个 TextView 或整行。 现在只有最后一个 TextView 被设置为 ltgray,无论用户按下什么电视。根据代码,我的假设是我可以通过代码中 x 的索引将每台电视设置为一个 onclick 值:但这不起作用。我不能通过 x 访问每个 textViewB 吗?该代码显示了为其他情况设置的 tvB,但这是设置所有 TextView 的文本背景的新情况。我不想要行背景。这很容易并且有效。但只有边框显示。我需要的是更改该表行中所有 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 中。您已经有了 View ,只需更改单击的 View 。例如:
@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();
}
关于android - 动态设置textview背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39006066/