Public Methods
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
Since:
API Level 1
Callback method to be invoked when an item in this AdapterView has been clicked.
Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.
Parameters
parent | The AdapterView where the click happened. |
---|---|
view | The view within the AdapterView that was clicked (this will be a view provided by the adapter) |
position | The position of the view in the adapter. |
id | The row id of the item that was clicked. |
參數:
parent:哪個AdapterView(可能會有多個ListView,區分多個ListView)
view:你點擊的Listview的某一項的內容,來源於adapter。如用((TextView)view).getText().toString(),可以取出點擊的這一項的內容,轉為string類型。
position:是adapter的某一項的位置,如點擊了listview第2項,而第2項對應的是adapter的第2個數值,那此時position的值就為1了。
id:值為點擊了Listview的哪一項對應的數值,點擊了listview第2項,那id就等於1。一般和position相同。
注:這些數值都是從0開始的。
實例:
布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.listviewonitemclickdemo.MainActivity" > <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </LinearLayout>
代碼:

package com.example.listviewonitemclickdemo; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends ActionBarActivity implements OnItemClickListener { private ListView listView; private ArrayAdapter<String> mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1); mAdapter.add("1視圖"); mAdapter.add("2視圖"); mAdapter.add("3視圖"); mAdapter.add("4視圖"); mAdapter.add("5視圖"); mAdapter.add("6視圖"); mAdapter.add("7視圖"); mAdapter.add("8視圖"); mAdapter.add("9視圖"); listView = (ListView) findViewById(R.id.listView); listView.setAdapter(mAdapter); listView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("h_bl", "parent=" + parent.getId()); Log.d("h_bl", "ListView.id=" + R.id.listView); Log.d("h_bl", "相等?" + (parent.getId() == R.id.listView)); Log.d("h_bl", "view=" + ((TextView) view).getText().toString()); Log.d("h_bl", "position=" + position); Log.d("h_bl", "id=" + id); } }
結果: