问题
First I create a background color for listview items like below, I have two custom listview like this:
My custom list for setting color:
Code:
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
final View rowView;
rowView = inflater.inflate(R.layout.table_one, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.tv.setText(result[position]);
rowView.setBackgroundColor(Color.WHITE);
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (position == 0) {
rowView.setBackgroundColor(Color.BLUE);
MainActivity.counter = Color.BLUE;
} else if (position == 1) {
rowView.setBackgroundColor(Color.YELLOW);
MainActivity.counter = Color.YELLOW;
} else if (position == 2) {
rowView.setBackgroundColor(Color.GREEN);
MainActivity.counter = Color.GREEN;
} else if (position == 3) {
rowView.setBackgroundColor(Color.MAGENTA);
MainActivity.counter = Color.MAGENTA;
}
}
});
return rowView;
}
When user click on listview it changes to specifed color as above image,
i need to get the color of listview saved in the list when click teh button.
How can i do that, Need help pls
In my MainActivity I have button ,
check = (Button) findViewById(R.id.check);
check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
}
});
回答1:
If you want to obtain a view background colour, from a ListView
ListView listView = (ListView) findViewById(R.id.my_list);
to obtain background try
Drawable listDrawableBackground = listView.getBackground();
if background is a colour, to obtain the colour, you can try
ColorDrawable listViewColor = (ColorDrawable) listView.getBackground();
to get the actual colour, use
int colorId = listViewColor.getColor();
you can compare this colorId with existing color like so:
if (colorID == R.color.blue) {
Log("color is blue");
}
Another way will be to add a tag to the ListView, and the tag will be the color, say
tag = "#ccc", and you can use
String colorCode = (String)listView.getTag();
now you have the colorCode and you can reuse it anywhere in your program.
来源:https://stackoverflow.com/questions/35314664/android-get-background-color-of-listviewitem-programmatically