1

我在 Android 中做了一个简单的 ListView Demo。What I want is that when an item from the list is selected it should be displayed on the next activity,I have tried the following code:

act1.java

package com.example.listview;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
ListView ls;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ls=(ListView)findViewById(R.id.lv);
        String[] s = {"Ahmedabad","Baroda","Chndigarh","Delhi","Jharkhand","Hariyana","Ilahabad","jammu","kashmir","Ludhina","Mysore","Nagpur",
                        "odisha","Puri","Raipur","Surat","Triveni","Udaipur","varanasi"};

        //final ArrayList<String> list =  new ArrayList<String>();

            ls.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,s));
            ls.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(MainActivity.this,Activity2.class);
                    String city=(String) ls.getSelectedItem();
                    Bundle b =new Bundle();
                    intent.putExtra("city", city);

                    startActivity(intent);

                }

            });


        }
    }

act2.java

package com.example.listview;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class Activity2 extends Activity {
TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity2);
        tv=(TextView)findViewById(R.id.textView1);
        Intent i =getIntent();
        Bundle b =getIntent().getExtras();
        String city =b.getString("city");
        tv.setText(city);
    }



}

请帮助...谢谢。

4

1 回答 1

0

而不是这个

 String city=(String) ls.getSelectedItem();

用这个

 String city=arg0.getItemAtPosition(position);
于 2013-05-02T17:19:39.200 回答