大家好,又见面了,我是你们的朋友全栈君。
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView listView;
private MyAdapter adapter;
private List<Person> list;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=findViewById(R.id.listview);
//给集合赋值
getData();
//初始化adapter
adapter = new MyAdapter(this,list);
//给listview设置适配器
listView.setAdapter(adapter);
//listview的item点击监听
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Person person = list.get(position);
Toast.makeText(MainActivity.this,person.mContent,Toast.LENGTH_SHORT).show();
}
});
}
//手动给集合赋值数据
private List<Person> getData(){
list = new ArrayList<Person>();
for(int i=1;i<=10;i++){
Person p = new Person(R.drawable.ic_launcher,i+"","第"+i);
list.add(p);
}
return list;
}
}
MyAdapter
public class MyAdapter extends BaseAdapter {
private Context context;
private List<Person> list;
//构造函数,给集合赋值
public MyAdapter(Context context,List<Person> list){
this.context=context;
this.list=list;
}
private class ViewHolder{
ImageView imageView;
TextView title;
TextView content;
}
@Override
public int getCount() {
//listview中显示的个数
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
//判断界面是否有缓存
if(convertView==null){
viewHolder= new ViewHolder();
//初始化item的控件
convertView= LinearLayout.inflate(parent.getContext(), R.layout.item, null);
viewHolder.imageView=convertView.findViewById(R.id.imageview);
viewHolder.title=convertView.findViewById(R.id.title);
viewHolder.content=convertView.findViewById(R.id.content);
convertView.setTag(viewHolder);
}else{
viewHolder=(ViewHolder)convertView.getTag();
}
//给item控件赋值
Person person = list.get(position);
viewHolder.imageView.setBackgroundResource(person.mPicture);
viewHolder.title.setText(person.mTitle);
viewHolder.content.setText(person.mContent);
return convertView;
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<!--divider属性设置item间距-->
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
效果图
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160577.html原文链接:https://javaforall.cn