布局文件
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv"
/>
创建Item_Layout.xml 文件 、编辑为 ListView 显示的格式
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/iv_img"
android:background="@drawable/ic_baseline_settings_24"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="雨中漫步"
android:id="@+id/tv_title"
android:layout_toRightOf="@id/iv_img"
android:textSize="30sp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_body"
android:text="人生就像旅行"
android:layout_below="@id/tv_title"
android:layout_toRightOf="@id/iv_img"
android:padding="30dp"
/>
</RelativeLayout>
创建实体类(JavaBean)、存放数据要显示的数据
public class ItemBean {
private String title;
private String content;
private int imgResId;
}
创建适配器继承BaseAdapter、实现4个方法
//数据源
private List<ItemBean> itemBeans;
//布局数据源
private LayoutInflater layoutInflater;
//上下文
private Context context;
public MyAdapter(Context context , List<ItemBean> itemBean) {
this.context = context;
this.itemBeans = itemBean;
layoutInflater = LayoutInflater.from(context);
}
//为ListView显示内容
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
//创建每一个条目
view = layoutInflater.inflate( R.layout.list_item_layout , viewGroup , false);
//找到条目里面控件Id
ImageView imageView = view.findViewById(R.id.iv_img);
TextView textViewTitle = view.findViewById(R.id.tv_title);
TextView textViewBody = view.findViewById(R.id.tv_body);
//拿到数据
ItemBean itemBean = itemBeans.get(i);
//为控件设置要显示的内容
imageView.setImageResource(itemBean.getImgResId());
textViewTitle.setText(itemBean.getTitle());
textViewBody.setText(itemBean.getContent());
//最后返回条目
return view;
}
最后Activity代码
//声明控件
private ListView listView;
private List<ItemBean> itemBeans;
private MyAdapter myAdapter;
初始化控件
private void initView() {
listView = findViewById(R.id.lv);
}
准备数据(也可以请求网络中的然后Json解析)
private void initData() {
//创建数组
itemBeans = new ArrayList<>();
//准备数据
ItemBean itemBean1 = new ItemBean();
itemBean1.setTitle("我是i但撒谎嗲是丢啊是大i撒谎的奥萨蒂还大还大阿萨");
itemBean1.setContent("ldksudoijclxjd4fef51er35f1");
//数据添加到数组中
itemBeans.add(itemBean1);
}
实例化Adapter
private void initAdapter() {
myAdapter = new MyAdapter(this,itemBeans);
//为ListView绑定Adapter
listView.setAdapter(myAdapter);
//绑定点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//获取条目内容、进行其他操作
ItemBean itemBean = itemBeans.get(i);
}
});
}
浙公网安备 33010602011771号