ListItem不显示在android中的第二个活动中

时间:2013-05-02 17:17:15

标签: android android-listview android-arrayadapter listitem

我在Android中做了一个简单的ListView演示。我想要的是,当选择列表中的项目时,它应显示在下一个活动上,我尝试了以下代码:

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



}

请帮忙......谢谢。

1 个答案:

答案 0 :(得分:0)

而不是

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

使用此

 String city=arg0.getItemAtPosition(position);