安卓自定义一个ListView

时间:2022-07-03 19:44:11

主布局文件:只有一个listview,用于显示所有的list

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listview1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="2dp"/>

</LinearLayout>

次布局文件:用户显示一个listview的一个list项:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="45dp">

<ImageView
android:id="@+id/imageview1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFFFFF"/>
<!--android:src="@drawable/callphone"-->


<TextView
android:id="@+id/textview1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:gravity="left|center"
android:layout_centerInParent="true"
android:textSize="25sp"
android:background="#FFFFFF"
/>
<!--android:text="13595436233"-->

<ImageView
android:id="@+id/imageview2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFFFFF"/>
<!--android:src="@drawable/callphone1"-->
</LinearLayout>
保存项目的类:
package com.example.wanglunhui.phonebook1;

import android.graphics.Bitmap;

/**
* Created by wanglunhui on 2017-03-08.
*/

public class PhoneBookSave {
private Bitmap mImage1;
private String mString;
private int mImage2;

public Bitmap getImage1() {
return mImage1;
}

public void setImage1(Bitmap image1) {
mImage1 = image1;
}

public String getString() {
return mString;
}

public void setString(String string) {
mString = string;
}

public int getImage2() {
return mImage2;
}

public void setImage2(int image2) {
mImage2 = image2;
}

public PhoneBookSave(Bitmap image1, String string, int image2) {
mImage1 = image1;
mString = string;
mImage2 = image2;
}
}
列表的适配器:
package com.example.wanglunhui.phonebook;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast;import java.util.List;import static android.os.Build.VERSION_CODES.M;/** * Created by wanglunhui on 2017-03-08. */public class PhoneBookAdapter extends ArrayAdapter<PhoneBookSave> {    private int resourceId;    @Override    public View getView(int position, View convertView, ViewGroup parent) {        final PhoneBookSave phoneBookSaveItem = getItem(position);        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);//获取View ImageView imageView1 = (ImageView) view.findViewById(R.id.imageview1);//将组件实例化,必须实例化 TextView textView1 = (TextView) view.findViewById(R.id.textview1);//将组件实例化,必须实例化 ImageView imageView2=(ImageView)view.findViewById(R.id.imageview2); //将组件实例化,必须实例化 //imageView1.setImageResource(phoneBookSaveItem.getImage1());//设置组件内容 imageView1.setImageBitmap(phoneBookSaveItem.getImage1());        imageView1.setOnClickListener(new View.OnClickListener() {//注意写ListView的点击事件实在Adapter里面写而MainActivity里面写的是整个ListView的事件 @Override            public void onClick(View view) {                Toast.makeText(MainActivity.mContext, "点击了联系人图片", Toast.LENGTH_SHORT).show();            }        });        textView1.setText(phoneBookSaveItem.getString());//设置组件内容 textView1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Toast.makeText(MainActivity.mContext, "点击的电话号码为:"+phoneBookSaveItem.getString(), Toast.LENGTH_SHORT).show();            }        });        imageView2.setImageResource(phoneBookSaveItem.getImage2());//设置组件内容 imageView2.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Toast.makeText(MainActivity.mContext, "点击了打电话", Toast.LENGTH_SHORT).show();                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.mContext)                        .setTitle("确定?")                        .setIcon(R.mipmap.ic_launcher)                        .setMessage("确定打电话给:"+phoneBookSaveItem.getString()+"?")                        .setPositiveButton("是", new DialogInterface.OnClickListener() {                                    @Override                                    public void onClick(DialogInterface dialogInterface, int i) {                                        Toast.makeText(MainActivity.mContext, "正在打电话", Toast.LENGTH_SHORT).show();                                        Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneBookSaveItem.getString()));                                        try {                                            MainActivity.mContext.startActivity(intent1);                                        }catch (Exception e){                                            e.printStackTrace();                                        }                                    }                                })                        .setNegativeButton("否", new DialogInterface.OnClickListener() {                            @Override                            public void onClick(DialogInterface dialogInterface, int i) {                                Toast.makeText(MainActivity.mContext, "点击了取消", Toast.LENGTH_SHORT).show();                            }                        });                builder.create().show();            }        });        return view;//返回视图View,这里它只是ListView的一行 }    public PhoneBookAdapter(Context context, int resourceId, List<PhoneBookSave> objects) {//构造函数,顺便记录resourceId //context是前面传入的上下文Context,resourceId可以显示一行文字的一个布局文件的Id,所以这里需要记录它而放在getView()中使用,objects是数据源 super(context, resourceId, objects);        this.resourceId = resourceId;    }}

列表的也可以用下面代码适配器:
package com.example.wanglunhui.phonebook1;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

import static android.os.Build.VERSION_CODES.M;

/**
* Created by wanglunhui on 2017-03-08.
*/

public class PhoneBookAdapter extends ArrayAdapter<PhoneBookSave> {
private int resourceId;
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final PhoneBookSave phoneBookSaveItem = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);//获取View
viewHolder = new ViewHolder();
viewHolder.linkmanPhoto=
(ImageView)view.findViewById(R.id.imageview1);
viewHolder.linkmanName=
(TextView)view.findViewById(R.id. textview1 );
viewHolder.callIocn = (ImageView)view.findViewById(R.id. imageview2 );
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.linkmanPhoto.setImageBitmap(phoneBookSaveItem.getImage1());
viewHolder.linkmanPhoto.setOnClickListener(new View.OnClickListener() {//注意写ListView的点击事件实在Adapter里面写而MainActivity里面写的是整个ListView的事件
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.mContext, "点击了联系人图片", Toast.LENGTH_SHORT).show();
}
});
viewHolder.linkmanName.setText(phoneBookSaveItem.getString());//设置组件内容
viewHolder.linkmanName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.mContext, "点击的电话号码为:"+phoneBookSaveItem.getString(), Toast.LENGTH_SHORT).show();
}
});
viewHolder.callIocn.setImageResource(phoneBookSaveItem.getImage2());//设置组件内容
viewHolder.callIocn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.mContext, "点击了打电话", Toast.LENGTH_SHORT).show();

AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.mContext)
.setTitle("确定?")
.setIcon(R.mipmap.ic_launcher)
.setMessage("确定打电话给:"+phoneBookSaveItem.getString()+"?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.mContext, "正在打电话", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneBookSaveItem.getString()));
try {
MainActivity.mContext.startActivity(intent1);
}catch (Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.mContext, "点击了取消", Toast.LENGTH_SHORT).show();
}
});
builder.create().show();

}
});
return view;//返回视图View,这里它只是ListView的一行


}

public PhoneBookAdapter(Context context, int resourceId, List<PhoneBookSave> objects) {//构造函数,顺便记录resourceId
//context是前面传入的上下文Context,resourceId可以显示一行文字的一个布局文件的Id,所以这里需要记录它而放在getView()中使用,objects是数据源
super(context, resourceId, objects);//这里的Object会自动由上面的getItem(position)来获取
this.resourceId = resourceId;
}

class ViewHolder {
ImageView linkmanPhoto;
TextView linkmanName;
ImageView callIocn;
}
}
getView()方法中的convertView参数用于将之前加载好的布局进行缓存,
以便之后可以进行重用。因此,如果在getView()方法中对convertView
进行判断,如果cnvertView为null,则使用layoutInflater加载布局,如
果不为null则直接对convertView进行重用,从而提高ListView的运行效
率。
新增的内部类ViewHolder用于对控件的实例进行缓存,从而避免每次
都通过findViewById()方法获取控件实例。
所以第二个适配器比第一个适配器效率更高。
主Activity:

package com.example.wanglunhui.phonebook1;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ListView;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

/**获取库Phon表字段**/
private static final String[] PHONES_PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID };

/**联系人显示名称**/
private static final int PHONES_DISPLAY_NAME_INDEX = 0;

/**电话号码**/
private static final int PHONES_NUMBER_INDEX = 1;

/**头像ID**/
private static final int PHONES_PHOTO_ID_INDEX = 2;

/**联系人的ID**/
private static final int PHONES_CONTACT_ID_INDEX = 3;

/**联系人名称**/
private ArrayList<String> mContactsName = new ArrayList<String>();

/**联系人电话**/
private ArrayList<String> mContactsNumber = new ArrayList<String>();

/**联系人头像**/
private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();

/**联系人头像ID**/
private ArrayList<Integer> mContactsPhontoID=new ArrayList<Integer>();

private List<PhoneBookSave> lists=new ArrayList<PhoneBookSave>();

public static Context mContext;//定义全局Context

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=MainActivity.this;//保存全局Context
getPhoneContacts();//获取电话信息
Initaial();
ListView listView=(ListView)findViewById(R.id.listview1);
PhoneBookAdapter adapter=new PhoneBookAdapter(MainActivity.this, R.layout.list_item, lists);
listView.setAdapter(adapter);
// listView.setOnClickListener(new View.OnClickListener() {//注意写ListView的点击事件实在Adapter里面写而MainActivity里面写的是整个ListView点击的的事件
// @Override
// public void onClick(View view) {
//
// }
// });
}

/**得到手机通讯录联系人信息**/
private void getPhoneContacts() {
ContentResolver resolver = this.getContentResolver();
// 获取手机联系人
Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
//得到手机号码
String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
//当手机号码为空的或者为空字段 跳过当前循环
if (TextUtils.isEmpty(phoneNumber))
continue;
//得到联系人名称
String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);

//得到联系人ID
Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);

//得到联系人头像ID
int photoid = new Long(phoneCursor.getLong(PHONES_PHOTO_ID_INDEX)).intValue();

//得到联系人头像Bitamp
Bitmap contactPhoto = null;

//photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
if(photoid > 0 ) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
contactPhoto = BitmapFactory.decodeStream(input);
}else {
contactPhoto = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
}

mContactsName.add(contactName);
mContactsNumber.add(phoneNumber);
mContactsPhonto.add(contactPhoto);
mContactsPhontoID.add(photoid);
}
phoneCursor.close();
}
}

public void Initaial(){
for(int i=0;i<mContactsName.size();i++){
PhoneBookSave phoneBookSave=new PhoneBookSave(mContactsPhonto.get(i),mContactsNumber.get(i),R.drawable.callphone);
lists.add(phoneBookSave);
}
}
}