美文网首页
Android 列表控件的使用(Listview/recycle

Android 列表控件的使用(Listview/recycle

作者: 码农耕 | 来源:发表于2019-05-27 22:44 被阅读0次

1.Listview的使用

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<String> dataArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置数据
        dataArray = new ArrayList<>();
        for (int i = 0;i<10;i++){
            dataArray.add("苹果");
            dataArray.add("雪梨");
            dataArray.add("柿子");
            dataArray.add("香蕉");
        }

        // 从布局文件中获取listview
        listView = findViewById(R.id.listview);

        // 设置适配器(第一个参数:上下文;第二个参数:listview的每一个item的布局文件,这里使用系统提供的;第三个参数:数据源)
        ArrayAdapter<String> adapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_list_item_1, dataArray);

        // 给listview设置适配器
        listView.setAdapter(adapter);
    }
}

2.ListView的item点击事件

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "点击了第"+position+"个item,内容是:"+dataArray.get(position), Toast.LENGTH_SHORT).show();
            }
        });
Screenshot_2019-05-27-22-43-29.png

3.listview的自定义适配器

public class FruitAdapter extends ArrayAdapter<Friut> {

    private int resourceId;

    public FruitAdapter(Context context, int textViewResourceId, List<Friut>objects){
        super(context,textViewResourceId,objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View converView, ViewGroup parent){
        Friut model = getItem(position);
        View view;
        if (converView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false );
        }else {
            view = converView;
        }
        ImageView icon = view.findViewById(R.id.icon);
        TextView titleView = view.findViewById(R.id.title);
        TextView descView = view.findViewById(R.id.desc);
        Button btn = view.findViewById(R.id.btn);
        titleView.setText(model.getName());
        descView.setText(model.getDesc());
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        return view;
    }
}

新建数据模型

public class Friut {
    private String name;
    private String desc;
    private int ID;

    // 构造方法
    public Friut(String name,String desc){
        this.name = name;
        this.desc = desc;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

    public String getDesc() {
        return desc;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

控制器设置

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private ArrayList<Friut> dataArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 设置数据
        dataArray = new ArrayList<>();
        for (int i = 0;i<10;i++){
            dataArray.add(new Friut("西瓜", "又大又圆"));
            dataArray.add(new Friut("苹果", "又红又甜"));
            dataArray.add(new Friut("橘子", "甜甜酸酸"));
            dataArray.add(new Friut("香蕉", "真好吃"));
        }

        listView = findViewById(R.id.listview);

        FruitAdapter adapter = new FruitAdapter(MainActivity.this,  R.layout.listview_item, dataArray);
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_list_item_1, dataArray);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "点击了第"+position+"个item,内容是:"+dataArray.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

item的布局文件:listview_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:id="@+id/list_item"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/icon"
        android:background="#FF00"
        android:layout_width="60dp"
        android:layout_height="60dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:layout_weight="1"
        android:layout_height="60dp">

        <TextView
            android:layout_width="wrap_content"
            android:id="@+id/title"
            android:textSize="20dp"
            android:text="标题"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="wrap_content"
            android:id="@+id/desc"
            android:text="这个人很懒什么都没有写!"
            android:textSize="15dp"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <Button
        android:layout_width="60dp"
        android:gravity="center"
        android:text="关注"
        android:id="@+id/btn"
        android:layout_height="50dp" />

</LinearLayout>
效果图 Screenshot_2019-05-28-23-26-47.png

2.RecyclerView的使用
从Android 5.0开始,谷歌公司推出了一个用于大量数据展示的新控件RecylerView,可以用来代替传统的ListView,更加强大和灵活。RecyclerView的官方定义如下:

2.1 设置获取RecyclerView
在MainActivity的布局中添加RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.support.v7.widget.RecyclerView
        android:id="@+id/recycleview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

并且通过id获取到RecyclerView

RecyclerView recycleview = (RecyclerView)findViewById(R.id.recycleview);

2.setLayoutManager

recycleview.setLayoutManager(new StaggeredGridLayoutManager(2 , StaggeredGridLayoutManager.VERTICAL));

第一个参数代表recycleview有多少列,第二个参数代表方向。
3.setAdapter
mAdapter = new myAdapter(getApplicationContext(),mUrls);
recycleview.setAdapter(mAdapter);
以下是适配器代码

public class myAdapter extends RecyclerView.Adapter<myAdapter.ViewHolder> {
    private List<String> mItems;
    private Context mContext;

    public myAdapter(Context context, List<String> items) {
        super();
        mItems = items;
        mContext = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final String url = mItems.get(position);
        Log.i("tag", "============onBindViewHolder url: " + url);
        Glide.with(mContext).load(url).placeholder(R.mipmap.ic_launcher).diskCacheStrategy(DiskCacheStrategy.RESULT)
                //.bitmapTransform(new CropCircleTransformation(mContext))  //如果想使用变换效果,这个注释可以打开
                .into(holder.image);
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(mContext,Main2Activity.class);
                intent.putExtra("url",url);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView image;

        public ViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.images);
        }
    }

}
// 给RecycleView加入滑动监听
recycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (isScrollToEnd(recycleview)) {
            Log.e("tag", "============scroll to end");
            index += 1;
            loadDatas(index);
        }
    }
});

//判断是否滑动到最后一个item
private boolean isScrollToEnd(RecyclerView recycleview) {
    if (recycleview == null) return false;
    if (recycleview.computeVerticalScrollExtent() + recycleview.computeVerticalScrollOffset() >= recycleview.computeVerticalScrollRange())
        return true;
    return false;
}

相关文章

网友评论

      本文标题:Android 列表控件的使用(Listview/recycle

      本文链接:https://www.haomeiwen.com/subject/sltltctx.html