Get value of item on OnItemClick Listview

◇◆丶佛笑我妖孽 提交于 2019-12-05 13:11:56

问题


I try to get the value of a selected Item within a custom adapter on a listview. I try this with following code:

public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {

                    View curr = parent.getChildAt((int) id);
                    TextView c = (TextView)curr.findViewById(R.id.tvPopUpItem);
                    String playerChanged = c.getText().toString();

                    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();

                }

At the beginning, if I click, the values are good, but once I scrolled and I click on another Item, I get the wrong value of that clicked item... Any idea what is causing this?


回答1:


The parameter v is the current row. so use:

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);
    String playerChanged = c.getText().toString();

    Toast.makeText(Settings.this,playerChanged, Toast.LENGTH_SHORT).show();
}

(Or you could use getChildAt(position) but this would be slower.)

Understand you might be able to simplify this more depending on your layout.




回答2:


Just Small Change is Required

TextView c = (TextView) v.findViewById(R.id.tvPopUpItem);

Since you are using custom view you need to pass the View argument in your OnItemClickListener then you need to use that value to get the Details of TextViews present in that




回答3:


listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent i=new Intent(ListOfAstrologers.this,AstroProForUser.class);
                i.putExtra("hello",adapter.getItem(position).getUsername() );
                startActivity(i);
            }
        });

Here username is a string field declared in a class and you must over ride getItem() method in adapter class to get the details of inflated row when you click.



来源:https://stackoverflow.com/questions/13405641/get-value-of-item-on-onitemclick-listview

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