2017.4.27
安卓作业:自定义Adapter
问题详见
使用ListView和自定义Adapter完成列表信息显示

思路详解
1.在主界面创建一个LinearLayout用于加载fragment
2.创建一个一列的自定义adapter
3.创建一个对象的xml布局
4.java语言编写:
(1)先创建一个对象接口,并定义我们所需的变量和变量获取数据和输出数据的方法。
(2)创建一个继承BaseAdapter的类,并且定义获取数据和视图的方法。
(3)增加相对应的数据
(4)在Activity类中静态创建,将数据加载进布局中
xml项
自定义adapter.xml
<GridView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="1" //确定为一列
android:stretchMode="columnWidth"
android:gravity="center"
android:id="@+id/fragment_gridview">
对象.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/xingming"
style="@style/text"
android:id="@+id/title1"/> //定义4个TextView即可
java编写
创建对象
1.先将所需的变量定义
private String title1;
private String title2;
private String title3;
private String title4;
2.将所有的getter和setter方法写入

3.添加对象的方法
public ClassInfo(String title1, String title2, String title3, String title4) {
this.title1=title1;
this.title2=title2;
this.title3=title3;
this.title4=title4;
}
获取数据和视图
1.创建的时候继承的父类选android.widget.BaseAdapter

2.添加所有相关的方法

3.定义数据和上下文变量
private List<ClassInfo> datas;
private Context context;
4.重写getView()方法
public View getView(int i, View view, ViewGroup viewGroup) {
//获取view
if(view==null){
view = LayoutInflater.from(context).inflate(R.layout.gridview_item,null);
}
TextView title1 =(TextView)view.findViewById(R.id.title1) ;
TextView title2 =(TextView)view.findViewById(R.id.title2) ;
TextView title3 =(TextView)view.findViewById(R.id.title3) ;
TextView title4 =(TextView)view.findViewById(R.id.title4) ;
ClassInfo classInfo = datas.get(i);
title1.setText(classInfo.getTitle1());
title2.setText(classInfo.getTitle2());
title3.setText(classInfo.getTitle3());
title4.setText(classInfo.getTitle4());//数据要与其方法对应
return view;
}
增加相对应的数据
List<ClassInfo> datas = new ArrayList<>(); //定义一个ClassInfo对象的List集合
datas.add(new ClassInfo("姓名:刘备","年龄:25","邮箱:liubei.qq.com","地址:南京市"));//增加数据
datas.add(new ClassInfo("姓名:关羽","年龄:24","邮箱:guanyu.qq.com","地址:南京市"));
datas.add(new ClassInfo("姓名:张飞","年龄:23","邮箱:zhangfei.qq.com","地址:南京市"));
datas.add(new ClassInfo("姓名:赵云","年龄:20","邮箱:zhaoyun.qq.com","地址:南京市"));
datas.add(new ClassInfo("姓名:马超","年龄:20","邮箱:machao.qq.com","地址:南京市"));
datas.add(new ClassInfo("姓名:黄忠","年龄:30","邮箱:huangzhong.qq.com","地址:南京市"));
final CustomGridViewAdapter adapter = new CustomGridViewAdapter(getActivity(),datas);
GridView gridView = (GridView)view.findViewById(R.id.fragment_gridview);
gridView.setAdapter(adapter);
return view;
静态创建
FragmentManager manager = getFragmentManager();
transaction = manager.beginTransaction();
if (gridViewFragment == null) {
gridViewFragment = new GridViewFragment();
transaction.add(R.id.show, gridViewFragment);
}
transaction.replace(R.id.show, gridViewFragment);
transaction.commit();
效果展示

注:注意数据的变量名与数据的id要相对应
浙公网安备 33010602011771号