问题
I created a simple Android ListView with an ArrayAdapter as shown below
ListView lView;
ArrayList<String> listItems;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lView = findViewById(R.id.mainListView);
listItems = new ArrayList<>();
updateView(42);
lView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
{
View v = lView.getChildAt(p3 - lView.getFirstVisiblePosition());
v.setBackgroundColor(R.color.blue); //ERROR , It changes the background color yea but also changes other ListView child's background
}
});
ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_list_item_1, android.R.id.text1,listItems);
lView.setAdapter(arrayAdapter);
}
void updateView(int x){
for(int i = 0; i<x; i++){
listItems.add("Dolapo");
listItems.add("mab");
listItems.add("jnr");
}
}
}
As I added in the comment Above, changing the Background color of One child View changes some others as well.
In the Process of trying to find out what's wrong, I added the line of code below in the OnItemClick method
TextView txt = (TextView) v;
Toast.makeText(getApplicationContext(),txt.getText(),0).show();
To my surprise, The toast message only reported one Item and that's the Text of the Element I clicked on. So how come setting the background color does something different?
来源:https://stackoverflow.com/questions/65266929/android-listview-getchild-not-working-properly