事实上,这很容易:
这是您在ListView上的活动,它实现了OnItemClickListener:
public class MainActivity extends Activity implements OnItemClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//* *EDIT* *
ListView listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
Log.i("HelloListView", "You clicked Item: " + id + " at position:" + position);
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, ListItemDetail.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
编辑
上面的代码将放在您的 MainActivity.java中。我将类的名称更改为 contentView - 这些名称是 Eclipse 中新创建的 Android 项目的名称。
另请参阅 //* Edit * 下的 2 个新行 - 这些行将设置侦听器以单击列表中的项目。MainActivity
setContentView(R.layout.activity_main)
您的activity_main.xml应如下所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:entries="@array/sections" >
</ListView>
</RelativeLayout>
“res/values/”文件夹中的数组.xml(不是字符串.xml)如下所示
<resources>
<string-array name="sections">
<item >Pro Constructive</item>
<item >Con Constructive</item>
<item >1st Speaker Cross</item>
<item >Pro Rebbutal</item>
<item >Con Rebuttal</item>
<item >2nd Speaker Cross</item>
<item >Pro Summary</item>
<item >Con Summary</item>
<item >Grand Cross</item>
<item >Pro Final Focus</item>
<item >Con Final Focus</item>
</string-array>
</resources>
注意:如果你复制并粘贴这个代码,它应该可以工作。但是,单击项目时会出现错误,因为您尚未创建项目。ListItemDetail.class
下面是一个示例,说明其外观:
您的列表项详细信息.java:
public class ListItemDetail extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listitem);
Intent intent = getIntent();
int position = intent.getIntExtra("position", 0);
// Here we turn your string.xml in an array
String[] myKeys = getResources().getStringArray(R.array.sections);
TextView myTextView = (TextView) findViewById(R.id.my_textview);
myTextView.setText(myKeys[position]);
}
}
及其activity_listitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/my_textview"/>
</LinearLayout>
如果您复制此代码,它将起作用。