如何在ListActivity中引用OnListItemClick

2024-01-19

我正在开发一个 Android 应用程序,但我遇到了困难ListActivity。我想要有一个不一样的Activity根据单击列表中的哪个项目开始。

我列了一个清单并引用它setListAdapter在java中,但我不知道如何在OnListItemClick。我想我需要参考列表中的位置。

With Activity and Buttons,我可以设置OnClickListener并使用switch声明与case对于每个Button。相当于什么ListActivity?

这是我的代码:

public class Options extends ListActivity implements {

    String myHistory[]= { "Item 1", "Item 2", "Item 3" };

    //---Set ListView---
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String> ( Options.this,
                                   android.R.layout.simple_list_item_1, myHistory)));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id); 

        //--if click position 1, do below
        //--Intent a = new Intent("show Item 1's corresponding page");
        //--startActivity(a);

        //--if click item in position 2, do below
        //--Intent b = new Intent("show Item 2's corresponding page");
        //--startActivity(b);

        //--if click item in position 3, do below
        //--Intent c = new Intent("show Item 3's corresponding page");
        //--startActivity(c);
    }
}

我不确定还有其他方法可以做到这一点,但我这样做: 我在活动类上设置了单击侦听器(而不是在适配器类上,我认为这更有意义)。 保存您要调用的类的数组:

Class[] classList = new Class[]{class1.class, class2.class....};

将监听器添加到列表视图

    lv.setOnItemClickListener(listviewClickListener());

然后是onItemClickListener方法:

private OnItemClickListener listviewClickListener() {
    OnItemClickListener clickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {


            //And then call the corresponing one
            Intent I= new Intent(thisActivity, classList[i]);
            int id = listOfObjects.get(position).getId();//do whatever you want with the object  on the postition "position"
            Bundle bundle = new Bundle();
            bundle.putInt("id", id);
            i.putExtras(bundle);
            thisActivity.startActivity(i);
        }
    };
    return clickListener;
}

我没有测试类文字数组,但我想它应该可以工作。

编辑:我正在考虑您想要为每个项目创建不同的活动(考虑它没有多大意义(没有上下文),因为列表视图上的所有项目都属于同一组,因此可能是以同样的方式使用)。否则,您不需要活动列表,只需将您想要的活动添加到意图中即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在ListActivity中引用OnListItemClick 的相关文章

随机推荐