【问题标题】:Event click on ListView (extends ListActivity)事件点击 ListView(扩展 ListActivity)
【发布时间】:2011-05-31 14:12:07
【问题描述】:

我有此代码,但当我单击列表中的项目时,我看不到该操作。 这段代码向我显示了关于 ArrayList profilesArrayList 的信息,但我不知道如何检查我从列表视图中选择的项目。谁能帮帮我?

profilesArrayList = new ArrayList<Profile>();
    profilesArrayList = copyProfilesToArrayList();
    ProfileAdapter adapter = new ProfileAdapter(
            getApplicationContext(), R.layout.profiles_item, profilesArrayList);

    listViewProfiles = (ListView)findViewById(android.R.id.list);
    listViewProfiles.setAdapter(adapter);

    listViewProfiles.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> a, View v, int position, long id) {
            switch(position) {
            case 0:

                Log.d("cardNumber", profilesArrayList.get(0).getCardNumber());

                break;

【问题讨论】:

  • 您的 switch 语句意味着您只会在单击列表中的第一项时记录。这真的是你想要的吗?
  • 是的,这是我想要的。对于不同的项目,我有不同的操作

标签: java android expandablelistview


【解决方案1】:

如果此代码的容器类是 ListActivity,只需覆盖该类的 onListItemClick,而不是将其设置为视图的 OnItemClickListener。这对我有用

public class ProfileList extends ListActivity
{
    private ArrayList<Profile> profilesArrayList;
    @Override 
    public void onCreate ( Bundle savedInstanceState )
    {
        super.onCreate(savedInstanceState);
        //populate your arraylist

        setListAdapter ( new ArrayAdapter<Profile>() );
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
        super.onListItemClick(l, v, position, id);
        Log.d("cardNumber", profilesArrayList.get(position).getCardNumber());
    }
}

【讨论】:

  • 我尝试过这种方法,但不起作用。我不知道为什么我可以在单击列表视图的地方进行操作:(
  • 我想我们可能都不太清楚是什么不适合你。一旦您进入 onListItemClick 函数,position 参数就是您单击的数组的索引。因此,在您的示例中,要获取单击的 Profile 对象,请执行 profilesArrayList.get(position);
  • 我无法理解我做错了什么。当我在模拟器中运行并单击一个项目时,项目不会说选中。我必须移动模拟器的键来选择一个项目,但仍然没有工作。
  • 项目没有像被选中一样亮?
  • 我正在尝试打印消息以进行调试,但仍然无法正常工作。它正在工作的列表视图,我在列表视图上看到了我的数据
【解决方案2】:

尝试使用 getSelectedItemPosition() 并添加 INVALID_POSITION 作为您可能的情况之一

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多