为GridView添加数据之后,我们需要在获取,当点击弄个按钮,或者某一行数据,我们需要获取当前的一些信息,通过gridview.setOnItemClickListener()
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long ip) {}
);
于onItemClick方法,下面详细说说。( 以下是官方的说明,参数命名不同而已,类型都是一样的。arg0=parent,arg1=view,arg2=position,arg3=id)
public abstract voidonItemClick(AdapterView<?> parent,View view, int position, long id)
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.
//当点击listview某一项时,这个回调方法就会被调用。
Parameters
parent | The AdapterView where the click happened.//你点击的AdapterView |
---|---|
view | The view within the AdapterView that was clicked (this will be a view provided by the adapter) //你点击的AdapterView的内容 |
position | The position of the view in the adapter. |
id | The row id of the item that was clicked. |
主要说说最后三个参数,
view——————是你点击的Listview的某一项的内容,来源于adapter。如用((TextView)arg1).getText(),可以取出点击的这一项的内容,转为string类型。
position————是adapter的某一项,如点击了listview第2项,而第2项对应的是adapter的第2个数值,那此时position的值就为1了。
如对应adapter的第3个数值,那此时position的值就为2了。
id———————id的值为点击了Listview的哪一项对应的数值,点击了listview第2项,那id就等于1。
注:这些数值都是从0开始的。
Button btn=(Button)arg0.getChildAt(i).findViewById(R.id.menuImage);
((TextView)arg1).getText()
package com.conowen.listview; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ListviewActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ListView lv = (ListView) findViewById(R.id.lv); String[] data = { "windows", "linux", "ios", "android", "wp7", "Symbian" };// 定义adapter lv.setAdapter(new ArrayAdapter<String>(this,// 把adapter绑定到listview里面 android.R.layout.simple_expandable_list_item_1, data)); // 点击事件 lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(ListviewActivity.this, "你点击的是第" + arg3 + "项", Toast.LENGTH_SHORT).show(); // 取出所点击的那一项的id } }); // 长按事件 lv.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub Toast.makeText(ListviewActivity.this, ((TextView) arg1).getText(), Toast.LENGTH_LONG).show(); // 取出点击listview某一项的内容 return false; } }); } }