android开发中listview的使用

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));
             函数的第二个参数就是有多少个列表项, getView的position参数就会是参数列表的长度

  • 在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(){

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值