Adapter:适配器-->将数据以什么形式发送到界面.
ΞBaseAdapter自定义及ListView的应用;
1.自定义BaseAdapter,重写其getView()方法;
ΞWife.java
public class Wife { private String aName; private String aSpeak; private int aIcon; public Wife() { } public Wife(String aName, String aSpeak, int aIcon) { this.aName = aName; this.aSpeak = aSpeak; this.aIcon = aIcon; } public String getaName() { return aName; } public String getaSpeak() { return aSpeak; } public int getaIcon() { return aIcon; } public void setaName(String aName) { this.aName = aName; } public void setaSpeak(String aSpeak) { this.aSpeak = aSpeak; } public void setaIcon(int aIcon) { this.aIcon = aIcon; }}
Ξ重写BaseAdapter;
public class WifeAdapter extends BaseAdapter { private LinkedListmData; //ArrayList和LinkedList都是实现了List接口的容器类,进行查操作时用ArrayList,进行增删操作的时候最好用LinkedList。 private Context mContext; public WifeAdapter(LinkedList mData, Context mContext) { this.mData = mData; this.mContext = mContext; } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //重写geiView() ViewHolder holder = null; if(convertView == null){ //由于会多次调用getView(),所以在此处判断,只需调用一次生成函数体(包括inflate()和findViewById())即可 convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_wife,parent,false); holder = new ViewHolder(); holder.img_icon = (ImageView) convertView.findViewById(R.id.img_icon); holder.txt_aName = (TextView) convertView.findViewById(R.id.txt_aName); holder.txt_aSpeak = (TextView) convertView.findViewById(R.id.txt_aSpeak); convertView.setTag(holder); //将Holder存储到convertView中,setTag(Onbect)表示给View添加一个格外的数据,以后可以用getTag()将这个数据取出来。 }else{ holder = (ViewHolder) convertView.getTag(); } holder.img_icon.setBackgroundResource(mData.get(position).getaIcon()); holder.txt_aName.setText(mData.get(position).getaName()); holder.txt_aSpeak.setText(mData.get(position).getaSpeak()); return convertView;}static class ViewHolder{ ImageView img_icon; TextView txt_aName; TextView txt_aSpeak; } }
ΞViewHolder是你自己造出来的一个类,配合convertView减少调用findViewById()的次数;
2.编写ListView;
mainActivity.java
public class MainActivity extends AppCompatActivity { private ListmData = null; private Context mContext; private WifeAdapter mAdapter = null; private ListView list_wife; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = MainActivity.this; list_wife = (ListView) findViewById(R.id.list_wife); mData = new LinkedList (); //添加元素 mData.add(new Wife("椎名真白", "呐,你想变成什么颜色?", R.drawable.hina)); mData.add(new Wife("泽村英梨梨", "都说了我没生气!", R.drawable.ilili)); mData.add(new Wife("加藤惠", "老公~", R.drawable.megumi)); mAdapter = new WifeAdapter((LinkedList ) mData, mContext); list_wife.setAdapter(mAdapter); }}
list_item_wife.xml
activity_main.xml
3.效果图;