簡體   English   中英

在ListView上打開活動

[英]Open Activity on ListView

我在Android編程世界中很新。 我正在使用此網站上的代碼,我想單擊圖像以打開一個新活動。 誰能幫我這個?

這是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"));

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);
}

為列表中的點擊添加監聽器

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

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

如果您還沒有,請查看ListView指南: Android開發人員ListView指南

該示例擴展了ListActivity並實現了onListItemClick。 在該方法中,創建一個Intent並調用startActivity。

這是另一個示例,其中包含大量信息,並且使用不同的方法來執行偵聽器: ListView教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM