在ListView上打开活动

时间:2014-05-14 14:34:51

标签: java android xml android-listview android-adapter

我是Android编程世界的新手。我使用this site中的代码,我想点击图片打开一个新活动。任何人都可以帮我这个吗?

这是xml:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:dividerHeight="0px"
tools:context=".StreamActivity" />

Java代码的第一部分:

public class StreamActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_stream);

    StreamAdapter adapter = new StreamAdapter(this);
    ((ListView) findViewById(R.id.main_list)).setAdapter(adapter);

    adapter.add(new StreamItem(this, R.drawable.photo1, "Option1", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo2, "Option2", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo3, "Option3", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo4, "Option4", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo5, "Option5", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo6, "Option6", "Click to open"));
    adapter.add(new StreamItem(this, R.drawable.photo7, "Option7", "Click to open"));

3 个答案:

答案 0 :(得分:0)

ListView.setOnItemClickListener。您可以让您的Activity实现界面,然后在listView.setOnItemClickListener(this);内调用onCreate()

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // create an Intent to open the next Activity.
    // If you need information from the selected item, use
    StreamItem item = adapter.getItem(position);
}

答案 1 :(得分:0)

为列表中的点击添加侦听器

yourList.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              

        Intent intent = new Intent(context, YourTargetClass.class);
        startActivity(intent);
    }
});

答案 2 :(得分:0)

如果您没有Android developer ListView guide

,请查看ListView指南

该示例扩展了ListActivity并实现了onListItemClick。在该方法中,创建一个Intent并调用startActivity。

这是另一个包含大量信息和不同方式来做听众的例子:ListView tutorial