先看效果图: 自定义Adapter: 主页面:
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List students =new ArrayList();
private int itemLayoutRes;
public CustomAdapter(Context mContext, List students, int itemLayoutRes) {
this.mContext = mContext;
this.students = students;
this.itemLayoutRes = itemLayoutRes;
}
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public List getStudents() {
return students;
}
public void setStudents(List students) {
this.students = students;
}
public int getItemLayoutRes() {
return itemLayoutRes;
}
public void setItemLayoutRes(int itemLayoutRes) {
this.itemLayoutRes = itemLayoutRes;
}
@Override
public int getCount() {//获得数据的条数
if(null!=students){
return students.size();
}
return 0;
}
@Override
public Object getItem(int position) {//获取每个item显示的数据对象
if(null!=students){
return students.get(position);
}
return null;
}
package com.example.day0318;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List students=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//准备数据
initDate();
//定义item布局文件(自定义)
//创建Adapter,绑定Adapter
CustomAdapter customAdapter=new CustomAdapter(this,students,R.layout.student_list_item);
ListView stuListView =findViewById(R.id.lv_students);
stuListView.setAdapter(customAdapter);
//设置监听器
}
public void initDate(){
Student stu1=new Student( "张三","2018012007",R.drawable.boy );
Student stu2=new Student("李四","2018012008",R.drawable.girl);
students.add(stu1);
students.add(stu2);
}
}
作者:池鱼之殃