简体   繁体   中英

Using a ListView to Switch to Different Activities

I have a Button on My Main Activity called Colours, it takes the user to a new activity with a ListView of Colours(Blue, Red, Yellow etc). On the Colours Activity I used a ListView and populated the entries using a string array xml. Problem is I do not know the code to write so I can select Colour Blue and be taken to a new activity called Blue or select Colour Red to switch to Red Activity etc.

Here's my sample, List.java

            package ng.com.degee;

                import android.app.Activity;
                import android.os.Bundle;


                public class List extends Activity {

                    @Override
                    protected void onCreate(Bundle savedInstanceState) {

                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.colourslist);


                    }


                }
`

Here's colourslist.xml

                `<?xml version="1.0" encoding="utf-8"?>
                <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical" >

                    <ListView
                        android:id="@+id/ColoursListView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:entries="@array/list_data" >

                    </ListView>

                </LinearLayout>`

Use listview onItemClickListener to direct different activities for listview items.

listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                 if(((TextView) view).getText().toString().equals("Blue")){
                    //Call Blue activity
                }else if(((TextView) view).getText().toString().equals("Red")){
                    //Call Red activity
                }
            }
        });

Try this.

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