1.直接在layout中声明listview
2.直接使用ListActivity的子类
这两种方法都可以使用listview
- 先定义listview中定义item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/logo"
android:layout_width="50px"
android:layout_height="50px"
android:layout_marginLeft="5px"
android:layout_marginRight="20px"
android:layout_marginTop="5px" >
</ImageView>
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="17sp" >
</TextView>
</LinearLayout>
- 定义adapter
public class MyArrayAdapter extends ArrayAdapter<String>
重写getView函数给创建的每个item如何赋值
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.custom_list, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
System.out.println(s);
if (s.equals("Red Android Logo")) {
imageView.setImageResource(R.drawable.android_logo_red);
} else if (s.equals("Green Android Logo")) {
imageView.setImageResource(R.drawable.android_logo_green);
} else if (s.equals("Yellow Android Logo")) {
imageView.setImageResource(R.drawable.android_logo_yellow);
}
return rowView;
}
- 调用适配函数setListAdapter(new MyArrayAdapter(this, Android_logos));
- 在listActivity的函数就是点击每项的相应函数@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
} - 或者设置listview的
mylistview.setOnItemClickListener(
new
OnItemClickListener(){