首先 你需要写一个ListView属性
在activity中调用Listview时,需要一个适配器,而这个适配器需要自己手动写入
下面将这个适配器命名为MyListAdapt
MyListAdapt需要继承自BaseAdapt 需要重写几个方法
其中getcount方法是设置你的列表内容个数
最重要的一个方法为getview 其中你的每一行长什么样子全靠其展示
这里要将你列表中的内容用一个xml布局进行展示
然后列表显示的便是你这个布局的列表
你在创建完布局之后,最好对布局进行实例化,例如
static class Viewholder{
public ImageView List_Image;
public TextView List_text1,List_text2,List_text3;
}
之后你便对getView方法进行编写
此方法主要是将这个列表与你写的布局进行连接
public View getView(int i, View view, ViewGroup viewGroup)
此方法有三个参数
其中view参数是列表中的具体内容
public class MyListAdapter extends BaseAdapter {
private Context mcontext;
private LayoutInflater mLayoutInflater;
public MyListAdapter (Context context){
this.mcontext = context;
mLayoutInflater = LayoutInflater.from(context);
}
//列表的长度return返回值是列表的长度
@Override
public int getCount() {
return 4;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
static class Viewholder{
public ImageView List_Image;
public TextView List_text1,List_text2,List_text3;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Viewholder viewholder = null;
if(view == null){
//通过mLayoutInflater对自己的布局与列表进行关联
view = mLayoutInflater.inflate(R.layout.layout_list_view,null);
//对自己的布局进行实例化
viewholder = new Viewholder();
viewholder.List_Image = view.findViewById(R.id.List_Image);
viewholder.List_text1 = view.findViewById(R.id.List_text1);
viewholder.List_text2 = view.findViewById(R.id.List_text2);
viewholder.List_text3 = view.findViewById(R.id.List_text3);
//将自己的布局传给view
view.setTag(viewholder);
}else
{
viewholder = (Viewholder) view.getTag();
}
//给控件赋值
viewholder.List_text1.setText("这里是标题");
viewholder.List_text2.setText("这里是时间");
viewholder.List_text3.setText("这里是介绍");
// Glide.with(mcontext).load("mipmap-xhdpi/bg.jpg").into(viewholder.List_Image);
return view;
}
}
接着在列表的activity里对列表实例进行操作
list_1.setAdapter(new MyListAdapter(ListviewActivity.this));
也可以设置点按长按事件
具体代码如下
list_1 = findViewById(R.id.list_1);
list_1.setAdapter(new MyListAdapter(ListviewActivity.this));
//设置点按事件
list_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//i代表的是当前被点击的是几号列表
}
});
//设置长按事件
list_1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
return true;
}
});
原创文章,作者:1402239773,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/272456.html