在ListView中,为什么我不断获取第一行而不是所选行的值? [英] Within a ListView, why do I keep getting the value of the first row instead of the selected row?

查看:104
本文介绍了在ListView中,为什么我不断获取第一行而不是所选行的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android应用中,我有以下代码:

In my android app I have the following code:

public void goToCaptureBonus (View View) {
        String tappedBonus = ((TextView) findViewById(R.id.bonusListCode)).getText().toString();
        Log.e(TAG,"goToCaptureBonus, tapped bonus = " + tappedBonus);
        Intent goToCaptureBonus = new Intent(this,captureBonus.class);
        goToCaptureBonus.putExtra("codeTapped",tappedBonus);
        startActivity(goToCaptureBonus);
    }

每当我点击一行时,日志总是显示第一行(在这种情况下为AK1).我知道ListView正在制作一行并重复它;但是每行的值确实可以正确显示.为什么上面的代码总是返回第一行,而不是返回被窃取的行中的值?

Whenever I tap on a row, the log always shows the first row (AK1 in this case). I get that ListView is making one row, and repeating it; but the values of each row do display correctly. Why does the above code always return the first row, rather than the value from the row that was tapped?

推荐答案

如果使用ListView,则应使用 OnItemClickListener .这是一个示例如何执行此操作.

In case of ListView you should use OnItemClickListener. Here is an example how to do this.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //use the position variable to get the list item from the list
        String selection = itemsArray[position]; // this will give the selected item 
    }
});

现在,只要轻按ListView上的某个项目,就会调用方法 onItemClick().在这里您可以获得选择.

Now whenever an item on your ListView is tapped, the method onItemClick() is called. And here you can get the selection.

这篇关于在ListView中,为什么我不断获取第一行而不是所选行的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆