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);
}
}
结果: