Question

Sorry for my english.

I'm using a list and I want each item I click on to send me to a different activity. With my code it sends me to the same activity for each item I select.

Example: I have Activity 1, Activity 2, and Activity 3. In the list I have 3 items: Item 1, Item 2, Item 3. When I click on Item 1 it sends me to Activity 1, same thing for Items 2 and 3. When I click to Item 2 I want to open Activity 2, and when I click on Item 3 I want to open Activity 3. I'm new with these so be kind with me ;)

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity1 extends ListActivity {

    static final String[] MENU = new String[] { "Ne salla", "Se shpejti", "Kinemate",
            "Rreth Nesh"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // no more this
        // setContentView(R.layout.list_fruit);

        setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_main_activity1,MENU));

        ListView listView = getListView();
        listView.setTextFilterEnabled(true);

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

                Intent intent = new Intent(getBaseContext(),NeSalla.class);
                startActivity(intent);   
            }
        });

    }

}

And in XML file

    <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="20sp" >
</TextView>
Was it helpful?

Solution

Use a switch statement using the position of the clicked item to choose which Activity to start.

listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent;
                switch(position) {
                    case 0:
                        intent = new Intent(getBaseContext(), NeSalla.class);
                        break;
                    case 1:
                        intent = new Intent(getBaseContext(), ...);
                        break;
                    ...
                }
                startActivity(intent);   
            }
        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top