简体   繁体   中英

Android: How to make List Items Clickable

I have just started looking into Android development and would like to make a list with clickable items. This is what I have so far in my 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>

My resource arrays.xml is:

    <?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>

And my MainActivity.java is:

public class MainActivity extends AppCompatActivity {

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

Thank you very much for your help.

First, you need to give your ListView an ID in the layout XML:

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

Then you'll need to call setOnItemClickListener on your ListView :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM