Android中自己设置一些记号(tag)

本例子是给MyBaseAdapter的构造方法中设置了一个参数String tag,
当绑定数据(实例化MyBaseAdapter对象)的时候传入不同的tag值,

在适合配中getView判断tag值绑定不同的布局文件。

项目结构:

Android中自己设置一些记号(tag)_第1张图片

核心代码:

MainActivity中

public class MainActivity extends Activity {
private ListView main_lv;
ArrayList> mydata=null;
String tag=null;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_lv=(ListView) findViewById(R.id.main_lv);



}

public void  btn1(View v){
tag="1";
//得到数据
List> data = getData1();
//实例化适配器对象传入数据
MyBaseAdapter adapter = new MyBaseAdapter(data, this,tag);
//listView绑定适配器
main_lv.setAdapter(adapter);

}
public void  btn2(View v){
tag="2";
//得到数据
List> data = getData1();
//实例化适配器对象传入数据
MyBaseAdapter adapter = new MyBaseAdapter(data, this,tag);
//listView绑定适配器
main_lv.setAdapter(adapter);
}



//  要放适配器上绑定的数据封装在方法中
private List> getData1() {


   mydata = new ArrayList>();
Map map1 = new HashMap();
        map1.put("name", "刘备");
        mydata.add(map1);


Map map2 = new HashMap();
map2.put("name", "关羽");
mydata.add(map2);


Map map3 = new HashMap();
map3.put("name", "张飞");
   mydata.add(map3);


Map map4 = new HashMap();
   map4.put("name", "黄忠");
mydata.add(map4);


Map map5 = new HashMap();
map5.put("name", "马超");
mydata.add(map5);


return mydata;
}



}//class

MyBaseAdapter中

public class MyBaseAdapter extends BaseAdapter {
List>mydata;
Context context;
String tag;
LayoutInflater inflater;


public MyBaseAdapter(List>mydata, Context context,String tag) {
this.mydata = mydata;
this.context = context;
        this.tag=tag;
}


@Override
public int getCount() {

return mydata.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mydata.get(position);
}


@Override
public long getItemId(int position) {


return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (tag.equals("1")) {
convertView=inflater.inflate(R.layout.main_items, null);
TextView tv=(TextView) convertView.findViewById(R.id.main_tv);

String tvStr = mydata.get(position).get("name").toString();
tv.setText(tvStr);
}
else if (tag.equals("2")) {
convertView=inflater.inflate(R.layout.other_items, null);
TextView tv=(TextView) convertView.findViewById(R.id.other_tv);
String tvStr = mydata.get(position).get("name").toString();
tv.setText(tvStr);

}





   return  convertView;
}


}//class

如果没有明白下载我的例子

例子1
http://download.csdn.net/detail/zhaihaohao1/8397137
例子2
http://download.csdn.net/detail/zhaihaohao1/8397591








你可能感兴趣的:(技巧,适配器)