Android ListView getChild() not working properly

梦想与她 提交于 2020-12-15 04:24:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!