Android自定义View及数据适配

来源:互联网 发布:数据库流程图怎么画 编辑:程序博客网 时间:2024/05/16 07:41

1. 编写自定义view的layout xml文件

例如:my_view.xml

<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:id="@+id/person"    android:orientation="vertical"      android:layout_width="fill_parent"      android:layout_height="fill_parent"      >      <ImageView    android:id="@+id/portrail"        android:layout_width="100dip"           android:layout_height="100dip"          android:layout_gravity="bottom|center_horizontal"          android:gravity="center|bottom"          android:background="#00FF00"          />        <TextView  android:id="@+id/name"android:layout_width="100dip"          android:layout_height="100dip"          android:layout_gravity="bottom|left"          android:gravity="left|top"          android:background="#FF0000"          android:text="@string/name"          />  </LinearLayout>  



2. 编写View类extends LinearLayout

例如:MyView.java

public class MyView extends LinearLayout implements android.content.DialogInterface.OnClickListener{protected ImageView portrail;    TextView name = null;public MyView(Context context) {super(context);// TODO Auto-generated constructor stubLayoutInflater.from(context).inflate(R.layout.my_view, this, true);  portrail = (ImageView) findViewById(R.id.portrail);name = (TextView) findViewById(R.id.name);}public void setPortrail(Bitmap bmp){portrail.setImageBitmap(bmp);}public void setName(String n){name.setText(n);}@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stub}}


3. 编写adapter

例如:MyAdapter.java

public class MyAdapter extends BaseAdapter{ArrayList<Expert> mLists = new ArrayList<Expert>();private Context mContext = null;public void append(ArrayList<Expert> mLists){mLists.addAll(mLists);notifyDataSetChanged();}public MyAdapter(Context context) {// TODO Auto-generated constructor stubsuper();mContext = context;}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn mLists.size();}@Overridepublic Object getItem(int arg0) {// TODO Auto-generated method stubreturn mLists.get(arg0);}@Overridepublic long getItemId(int arg0) {// TODO Auto-generated method stubreturn arg0;}@Overridepublic View getView(int arg0, View arg1, ViewGroup arg2) {// TODO Auto-generated method stubMyView mv = null;if(arg1 == null){mv = new MyView(mContext);}else{mv = (MyView)arg1;}String n = ;mv.setPortrail(mLists.get(arg0).portrail)mv.setName(mLists.get(arg0).name);return mv;}}


 

0 0