//Mactivity 需要封装
package com.example.cxk20170906;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView lv;
Madapter madapter;
ArrayList<Student> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取控件
lv=(ListView) findViewById(R.id.lv);
//添加数据
initData();
//添加适配器
madapter= new Madapter();
//添加到listview
lv.setAdapter(madapter);
}
private void initData() {
//创建集合
list = new ArrayList<Student>();
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
list.add(new Student("张三",0));
list.add(new Student("李四","20",1));
}
class Madapter extends BaseAdapter{
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
//优化
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int tipeid = list.get(position).getTipeid();
switch (tipeid){
case 0:
ViewHolder1 vh1;
if (convertView==null){
convertView= View.inflate(MainActivity.this,R.layout.list1,null);
vh1 = new ViewHolder1();
vh1.tv1=(TextView) convertView.findViewById(R.id.tv1);
convertView.setTag(vh1);
}else{
vh1=(ViewHolder1) convertView.getTag();
}
vh1.tv1.setText(list.get(position).getName());
break;
case 1:
ViewHolder2 vh2;
if (convertView==null){
convertView=View.inflate(MainActivity.this,R.layout.list2,null);
vh2 = new ViewHolder2();
vh2.tv2=(TextView) convertView.findViewById(R.id.tv2);
vh2.tv3=(TextView) convertView.findViewById(R.id.tv3);
convertView.setTag(vh2);
}else{
vh2=(ViewHolder2) convertView.getTag();
}
vh2.tv2.setText(list.get(position).getName());
vh2.tv3.setText(list.get(position).getAge());
break;
}
return convertView;
}
//返回条目的类型
@Override
public int getItemViewType(int position) {
return list.get(position).getTipeid();
}
//返回条目的类型个数
@Override
public int getViewTypeCount() {
return 2;
}
}
class ViewHolder1{
TextView tv1;
}
class ViewHolder2{
TextView tv2;
TextView tv3;
}
}