【问题标题】:Android: How to make List Items ClickableAndroid:如何使列表项可点击
【发布时间】:2016-05-07 22:07:37
【问题描述】:

我刚刚开始研究 Android 开发,并想制作一个包含可点击项目的列表。这就是我的 activity_main.xml 中的内容:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    >
    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:entries="@array/list_content">
    </ListView>
</LinearLayout>

我的资源 arrays.xml 是:

    <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="list_content">
        <item>Phase 1</item>
        <item>Phase 2</item>
        <item>Phase 3</item>
        <item>Phase 4</item>
    </string-array>
</resources>

而我的 MainActivity.java 是:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}}

非常感谢您的帮助。

【问题讨论】:

标签: android list


【解决方案1】:

首先,您需要在布局 XML 中为您的 ListView 提供一个 ID:

<ListView
    android:id="@+id/my_list_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:entries="@array/list_content">

然后您需要在您的ListView 上致电setOnItemClickListener

ListView myListView = (ListView) findViewById(R.id.my_list_view);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("MainActivity", "ListView item clicked.");
    }
});

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 2014-09-11
相关资源
最近更新 更多