在上一篇Android控件之ListView(一)中简单介绍了了ListView如何显示文字,接下来将介绍一下“图片+文字”组合使用的ListView,并为ListView添加事件处理,
Android控件之ListView(一)链接:
http://blog.csdn.net/liguangliang_bzu/article/details/49448803
如下图:
1.0 在layout文件夹下新建list_item.xml文件
list_item.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/contentDescription"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textview01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
2.0 在activity_main.xml文件中添加一个ListView控件
activity_main.xml:
<RelativeLayout 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"
tools:context="com.lgl.listview3.MainActivity" >
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
3.0 在MainActivity中做相应处理
MainActivity:
package com.lgl.listview3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ListView listView;
//定义一个String类型的数组
String[] items = new String[20];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//循环赋值
for(int i=0; i<items.length; i++) {
items[i] = "小怪兽" + i;
}
//绑定适配器
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.list_item, R.id.textview01, items);
listView.setAdapter(adapter);
//绑定监听
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(MainActivity.this, "您点击了第" + arg2 + "行!", Toast.LENGTH_SHORT).show();
}
});
}
}
总结:
在onItemClick方法中有四个参数
onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
引用官方的解释,翻译不准确,还请见谅
- arg0:The AdapterView where the click happened (表示当前点击的是哪个AdapterView )
- arg1:The view within the AdapterView that was clicked (this will be a view provided by the adapter)(表示AdapterView 中点击的哪个item)
- arg2:The position of the view in the adapter(表示你所点击的item在此adapter中的位置)
- arg4:The row id of the item that was clicked(表示点击的item是第几行)