Android:列表:如何获取列表中的每个项目以将其发送给其他活动?

时间:2014-05-04 20:52:01

标签: android listview android-activity

抱歉我的英文。

我正在使用列表,我希望我点击的每个项目都能将我发送到其他活动。 使用我的代码,它会将我发送给我选择的每个项目的相同活动。

示例:我有活动1,活动2和活动3.在列表中我有3个项目:项目1,项目2,项目3.当我点击项目1时,它将我发送到活动1,同样的事情第2项和第3项。当我点击第2项时,我想打开活动2,当我点击第3项时,我想打开第3项活动。我对这些很新,所以请跟我好心;)

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

    }

}

在XML文件中

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

1 个答案:

答案 0 :(得分:1)

使用switch语句,使用单击项的位置选择要启动的Activity。

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