效果图:
使用方法:
1、在布局文件中加入ListView控件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
2、新建一个列表项布局listView_item.xml,用于设计ListView条目的样式
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:id="@+id/ivIcon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/carrot" android:layout_gravity="center_vertical"/> <TextView android:id="@+id/tvName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="胡萝卜" android:layout_marginLeft="10dp"/> </LinearLayout>
3、自定义数据适配器继承BaseAdapter
import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class MyAdapater extends BaseAdapter { private int[] icons = {R.drawable.carrot, R.drawable.chilli, R.drawable.mushroom, R.drawable.potato, R.drawable.tomato}; private String[] names = {"胡萝卜","辣椒","香菇","土豆","西红柿"}; private Context context; public MyAdapater(Context context){ this.context = context; } //获取列表的个数 @Override public int getCount() { return names.length; } //获取列表项代表的对象 @Override public Object getItem(int position) { return null; } //获取列表项的ID @Override public long getItemId(int position) { return 0; } //获取列表项的视图 @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(context).inflate(R.layout.listview_item,null); //通过视图获取对应的控件 ImageView ivIcon = convertView.findViewById(R.id.ivIcon); TextView tvName = convertView.findViewById(R.id.tvName); //设置控件数据 ivIcon.setImageResource(icons[position]); tvName.setText(names[position]); return convertView; } }
4、添加数据源,并完成数据适配器
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; public class MainActivity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = findViewById(R.id.listView); //创建适配器对象 MyAdapater adapater = new MyAdapater(this); //设置适配器 listView.setAdapter(adapater); } }