如何在ListView.setOnItemClickListener中使用Intent启动Activity?

时间:2015-01-03 00:12:07

标签: java android listview android-intent android-activity

我想在点击Listview中的项目时开始新的活动。但是当点击一个项目时,没有任何反应。 Logcat消息中没有任何内容。这两个活动都在AndroidManifest中声明。

ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {   
        Intent myIntent = new Intent(view.getContext(), SecondActivity.class);
        myIntent.putExtra("test", "hello"); 
        startActivity(myIntent);
    }
});

4 个答案:

答案 0 :(得分:2)

首先,您需要在listView对象中设置ItemClick listener

ListView yourListView.setOnItemClickListener

然后您需要在Intent

中传递活动的上下文

Intent myIntent = new Intent view.getContext() ThisActivityName.this,SecondActivity.class);

代码段:

ListView yourListView = (ListView) findViewById(R.id.listviewid);
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {   
        Intent myIntent = new Intent(ThisActivityName.this, SecondActivity.class);
        myIntent.putExtra("test", "hello"); 
        startActivity(myIntent);
    }
});

希望它有助于ツ

答案 1 :(得分:0)

尝试使用ListView

final ListView list = (ListView) findViewById(R.id.list);
list.setItemsCanFocus(false);

另外,请确保CheckBox内的列表项设置为focusable false

android:focusable="false"
android:focusableInTouchMode="false"

来源:setOnItemClickListener() not working on custom ListView @ Android

答案 2 :(得分:0)

尝试使用此代码,

ListView listView=(ListView) findViewById(R.id.list);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {   
    Intent myIntent = new Intent(ActivityName.this, SecondActivity.class);
    myIntent.putExtra("test", "hello"); 
    startActivity(myIntent);
}
});

答案 3 :(得分:0)

对于ListView中的多个选项您可以使用以下代码。

 lv_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

            String s = lv_1.getItemAtPosition(position).toString();

            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();


            switch (position) {
                case 0:
                    Intent newActivity = new Intent(MainActivity.this, Android.class);
                    startActivity(newActivity);
                    break;
                case 1:
                    Intent newActivity1 = new Intent(MainActivity.this, Iphone.class);
                    startActivity(newActivity1);
                    break;
                case 2:
                    Intent newActivity2 = new Intent(MainActivity.this, Window.class);
                    startActivity(newActivity2);
                    break;



            }
        }

        ;

    });