ListView添加自定义适配器最优方案

时间:2022-02-18 22:42:11

Listview中  的属性 entries可以传入

 

<ListView
android:id="@+id/list_view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/name"
>

还可以设置分割线

 

android:entries="@array/name"
android:divider="#c22d2d"
android:dividerHeight="4dp"

 

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(MainActivity.this, "你选择了:"+names[position], Toast.LENGTH_SHORT).show();
    }
});

onItemClick中三个参数,1.ListView本身2.ListView列表项的View对象3.单击列表项显示的数据在数组中的位置4. 单机的列表项在ListView中的位置

 

TextView textview = (TextView) view.findViewById(android.R.id.text1);
Toast.makeText(MainActivity.this,"你选择了:"+textview.getText(),Toast.LENGTH_SHORT).show();

还可以通过view获取一个textView对象

 

 

 publicViewgetView(intposition,View convertView,ViewGroup parent) {
//        Person person =(Person) getItem(position);
//        View v = LayoutInflater.from(context).inflate(R.layout.main_item_1,null);//加载子项布局
//        TextView name = (TextView) v.findViewById(R.id.name);//绑定
//        TextView phone = (TextView) v.findViewById(R.id.phone);
//        name.setText(person.getName());
//        phone.setText(person.getPhone());
//        return v;
        Person person = (Person) getItem(position);
        View view;
        Viewholder viewholder;
        if(convertView==null){
            view = LayoutInflater.from(context).inflate(R.layout.main_item_1,null);
            viewholder = newViewholder();
            viewholder.name_text= (TextView)view.findViewById(R.id.name);
            viewholder.phone_text= (TextView) view.findViewById(R.id.phone);
            view.setTag(viewholder);
        }else{
            view = convertView;
            viewholder = (Viewholder) view.getTag();
        }
        viewholder.name_text.setText(person.getName());
        viewholder.phone_text.setText(person.getPhone());
        returnview;
    }
    classViewholder{
        TextViewname_text;
        TextViewphone_text;
    }