假设您希望包含可点击字符串的列表视图行。
listview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent i= new Intent("com.example.secondactivity");
i.putExtra("value", country[arg2]);
// pass country based on listview position
//value- is the key
// second parameter is the actual value ie country name
startActivity(i);
}
});
国家[arg2]。arg2 是列表视图的位置。列表视图中的项目是根据位置填充的。单击列表视图行时,国家[arg2] 是该列表视图位置中的国家/地区名称。因此,您使用意图将值传递给第二个活动。
在第二个活动的 onCreate() 中检索
Intent intent = getIntent();
Bundle b = intent.getExtras();
String country = b.getString(key);//value or china in youe case.
确保第二个活动在清单文件中有一个条目
编辑:
<activity
android:name="com.example.test1.secondactivity"
>
<intent-filter>
<action android:name="com.example.test1.secondactivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
带有列表视图的 MainActivity。
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] country = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// R.layout.listview_layout is the custom layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, country);
//this refers to the actiivty context,
//second parameters says its a simple list item
//third is id of text
//country is your array of string
ListView listView = (ListView) findViewById(R.id.lv);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i= new Intent("com.example.test1.secondactivity");
i.putExtra("value", country[arg2]);
// pass country based on listview position
//value- is the key
// second parameter is the actual value ie country name
startActivity(i);
}
});
}
}
具有文本视图的第二个 Activity。
public class secondactivity extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv= (TextView) findViewById(R.id.textView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String country = extras.getString("value");//value or china in youe case
tv.setText(country);
}
}
}
项目文件夹