依然是一个listView的Java文件
1 public class ListViewActivity extends Activity {
2 private ListView lv1;
3 @Override
4 protected void onCreate(@Nullable Bundle savedInstenceState) {
5
6 super.onCreate(savedInstenceState);
7 setContentView(R.layout.activity_listview);
8 lv1=findViewById(R.id.lv_1);
9 lv1.setAdapter(new MylistAdapter(ListViewActivity.this));
10 lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
11 @Override
12 public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
13 Toast.makeText(ListViewActivity.this, "点击pos:"+i, Toast.LENGTH_SHORT).show();
14 }
15 });
16 lv1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
17 @Override
18 public boolean onItemLongClick(AdapterView> adapterView, View view, int i, long l) {
19 Toast.makeText(ListViewActivity.this, "长按pos:"+i, Toast.LENGTH_SHORT).show();
20 return true;//这里如果返回false的话,处理完长按事件后还会处理点击事件,也就是说会弹出两个提示框,为了让他只显示一个对话框改为true
21 }
22 });
23 }
24 }
对应的activity_listview.xml文件
1
其中设置的点击效果xml文件为
1
这里面state_pressed和state_checked是不一样的,checked是选中的意思,pressed是按压时候的效果,注意区分。
然后layout_list_item.xml文件是设置list中每一个元素的样式结构的文件
1
41
然后建立MyListAdapter的Java文件来定义列表中每个元素的具体结构的值:
1 public class MylistAdapter extends BaseAdapter {
2 private Context context;
3 private LayoutInflater layoutInflater;
4 public MylistAdapter(Context context){
5 this.context=context;
6 layoutInflater=LayoutInflater.from(context);
7 }
8 @Override
9 public int getCount() {
10 return 10;
11 }//列表长度
12
13 @Override
14 public Object getItem(int i) {
15 return null;
16 }//不怎么用
17
18 @Override
19 public long getItemId(int i) {
20 return 0;
21 }//不怎么用
22
23 static class ViewHolder{
24 public ImageView imageview;
25 public TextView tvTitle,tvTime,tvContent;
26 }
27
28 @Override
29 public View getView(int i, View view, ViewGroup viewGroup) {
30 ViewHolder holder=null;
31 if(view==null){
32 view=layoutInflater.inflate(R.layout.layout_list_item,null);
33 holder=new ViewHolder();
34 holder.imageview=view.findViewById(R.id.imv);
35 holder.tvTitle=view.findViewById(R.id.tv_title);
36 holder.tvContent=view.findViewById(R.id.tv_content);
37 holder.tvTime=view.findViewById(R.id.tv_time);
38 view.setTag(holder);
39 }else{
40 holder= (ViewHolder) view.getTag();
41 }
42 //给控件赋值
43 holder.tvTitle.setText("我是大标题");
44 holder.tvTime.setText("2066-06-6");
45 holder.tvContent.setText("说点啥呢啥呢");
46 Glide.with(context).load("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png").into(holder.imageview);
47 return view;
48 }
49 }
手机扫一扫
移动阅读更方便
你可能感兴趣的文章