Paul Moore Paul Moore - 3 months ago 18
Android Question

dynamically setting textview background color

I have a table 'D' that each row has 4 textviews in it. I have set onlicklistener and it works. What I want is for the user to press on any text view of that row and the text background changes to ltgray. I will solve whether each textview or the whole row gets set.
Right now only the last textview gets set to ltgray no matter what tv the user presses. Based on the code my assumption is that I can set each tv to an onclick value by the index of x in the code: But that aint working. Cant I access each textViewB by the x?. The code shows the tvB getting set for other situations but this new one of setting the text background of all textviews. I dont want row background. That is easy and works. but only the borders show. My need is the text background to changes for all 4 tvs in that table row.
Thanks you in advance:

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();
}


Its all done in code. There are no xml or styles.

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

or

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

or

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

I believe what you want is in the onClickListener. You have already the view, just change that view clicked. For example:

@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();
}
Comments