美文网首页
《Android第一行代码》first reading 六

《Android第一行代码》first reading 六

作者: 威宸 | 来源:发表于2017-01-12 10:29 被阅读0次

    ListView绝对可以称得上是Android中最常用的控件之一。

    ListView的简单用法:

    首先listview是用来展示大量数据。那我们就应该先将数据提供好。当然数组中的数据是无法直接传给ListView的,这时候我们就需要适配器。例:ArrayAdapter。
    在ArrayAdapter的构造函数中依次传入当前上下文ListView子项布局的id
    以及要适配的数据。最后调用ListView的setAdapter()方法将构建好的适配器对象传递进去,就这样ListView和数据之间的关系就建立完成了。

    定制ListView的界面

    在大多数情况下,系统的ListView无法满足业务需求,这时候我们就需要对ListView的界面进行定制。

    举个例子:
    1. 定义一个实体类,作为ListView适配器的适配类型
    public class Fruit {
        private String name;
        private int imageId;
        ...
    }
    
    1. 为ListVIew的子项指定一个我们自定义的布局
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/fruit_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/fruit_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginLeft="10dp"/>
    </LinearLayout>
    
    1. 创建一个自定义的适配器,此适配器继承ArrayAdapter,并将泛型指向实体类:
    public class FruitAdapter extends ArrayAdapter<Fruit> {
        private int resourceId;
        LayoutInflater mInflater = null;
        public FruitAdapter(Context context , int textViewResourceId , List<Fruit> objects) {
            super(context,textViewResourceId,objects);
            resourceId = textViewResourceId;
        }
        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Fruit fruit = getItem(position);//获取当前项的Fruit实例
    //将加载好的布局进行缓存,可重用
            View view;
            ViewHolder viewHolder;
            if (convertView == null){
                view = mInflater.inflate(resourceId,parent,false);
                viewHolder = new ViewHolder();
                viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
                viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
                view.setTag(viewHolder);
            }else {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.fruitImage.setImageResource(fruit.getImageId());
            viewHolder.fruitName.setText(fruit.getName());
            return view;
        }
    //借助ViewHolder,将控件进行缓存,可重用
        class ViewHolder{
            ImageView fruitImage;
            TextView fruitName;
        }
    }
    
    1. MainActivity继承BaseActivity
    //BaseActivity
    public abstract class BaseActivity extends AppCompatActivity{
        protected Context mContext;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            this.mContext = this;
            int layoutId = getLayoutId();
            View contentView = LayoutInflater.from(mContext).inflate(layoutId,null,false);
            setContentView(contentView);
            hideActionBar();
            initData();
            initView();
            initList();
        }
        /**
         *初始化数据
         */
        public abstract void initData();
        /**
         *初始化界面
         */
        public abstract void initView();
        /**
         *隐藏标题栏
         */
        public void hideActionBar(){
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null){
                actionBar.hide();
            }
        }
        /**
         * 获取布局文件的id
         *
         * @return
         */
        public abstract int getLayoutId();
    }
    
    //MainActivity
    public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener{
        private List<Fruit> fruitList = new ArrayList<>();
        @Override
        public void initData() {
            for (int i = 0 ; i<2 ;i++){
                Fruit apple = new Fruit("Apple",R.drawable.apple_pic);
                fruitList.add(apple);
                Fruit banana = new Fruit("Banana",R.drawable.banana_pic);
                fruitList.add(banana);
                Fruit orange = new Fruit("Orange",R.drawable.orange_pic);
                fruitList.add(orange);
                Fruit watermelon = new Fruit("Watermelon",R.drawable.watermelon_pic);
                fruitList.add(watermelon);
                Fruit pear = new Fruit("Pear",R.drawable.pear_pic);
                fruitList.add(pear);
                Fruit grape = new Fruit("Grape",R.drawable.grape_pic);
                fruitList.add(grape);
                Fruit pineapple = new Fruit("Pineapple",R.drawable.pineapple_pic);
                fruitList.add(pineapple);
                Fruit strawberry = new Fruit("Strawberry",R.drawable.strawberry_pic);
                fruitList.add(strawberry);
                Fruit cherry = new Fruit("Cherry",R.drawable.cherry_pic);
                fruitList.add(cherry);
                Fruit mango = new Fruit("Mango",R.drawable.mango_pic);
                fruitList.add(mango);
            }
        }
        @Override
        public void initView() {
            FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
            ListView listView = (ListView) findViewById(R.id.list_view);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(this);
        }
        @Override
        public int getLayoutId() {
            return R.layout.activity_main;
        }
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //点击listView子项,弹出提示框显示该子项的Name
            Fruit fruit = fruitList.get(position);
            Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
        }
    }
    

    好至此就完成这个小例子了。

    更强大的滚动控件——RecyclerView:

    可以说RecyclerView是优化和强化过的ListView,Android官方也推荐使用RecyclerView。
    举个例子:

    1. RecyclerView也属于新增的控件,所以要先导包。
      在app/build.gradle中:
      compile 'com.android.support:recyclerview-v7:24.2.1'
    2. 仿上一个ListView例子:
      同样准备一个Fruit类和fruit_item.xml,新建一个FruitAdapter类,让这个类继承自RecyclerView.Adatper,并将泛型指定为FruitAdapter.ViewHolder。
    public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder>{
        private List<Fruit> mFruitList;
    /**
    *定义一个ViewHolder的类,在ViewHolder的构造函数中传入一个View参数,
     *这个参数通常为RecyclerView子项的最外层布局。
     */
        static class ViewHolder extends RecyclerView.ViewHolder{
            ImageView fruitImage;
            TextView fruitName;
            public ViewHolder(View itemView) {
                super(itemView);
                fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
                fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
            }
        }
    //构造函数,用于取数据源
        public FruitAdapter(List<Fruit> mFruitList) {
            this.mFruitList = mFruitList;
        }
    //用于创建ViewHolder实例。在此,我们将子项布局加载进来,然后传入构造函数,最后返回viewHolder。
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }
    //用于对RecyclerView子项的数据进行赋值,会在每个子项被滚动到屏幕内执行。
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Fruit fruit = mFruitList.get(position);
            holder.fruitImage.setImageResource(fruit.getImageId());
            holder.fruitName.setText(fruit.getName());
        }
    //子项的个数
        @Override
        public int getItemCount() {
            return mFruitList.size();
        }
    }
    
    1. MainActivity
    @Overridepublic void initView() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }
    

    初始化界面中,我们先获取到RecyclerView的实例,然后通过LinearLayoutManager对象以setLayoutManager()方法设置RecyclerView的布局方式(这里使用的LinearLayoutManager是线性布局的意思)
    然后实例一个adapter,通过setAdapter()完成适配器设置。

    实现横向滚动和瀑布流布局

    其实实现横向滚动很简单,就如上面的例子。我们只要设置layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL)就行了。

    RecyclerView能轻松实现这些效果的原因是RecyclerView的布局排列是交给LayoutManager管理的,而LayoutManager中制定了一套可扩展的布局排列接口,子类只要按接口规范来实现,就能制定出各种不同的排列方式的布局了。

    同样RecyclerView还提供了GridLayoutManager和StaggeredGridLayoutManager这两种内置的布局排列方式。
    GridLayoutManager:实现网格布局
    StaggeredGridLayoutManager:实现瀑布流布局

    实现瀑布流布局只要加这句就可以了StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
    参数一:指定布局的列数;参数二:指定布局的排列方向,这里是纵向。

    实现网格布局加这句:GridLayoutManager layoutManager = new GridLayoutManager(GridLayoutManager.VERTICAL,3);
    其参数与瀑布相似。

    RecyclerView的点击事件

    RecyclerView的所有的点击事件都由具体的View去注册。
    举个例子:

    ...
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
    //定义一个View接收子项的View
        View fruitView;
        public ViewHolder(View itemView) {
            super(itemView);
            fruitView = itemView;
            fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
            fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
        }
    }
    ...
    @Overridepublic
     ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder viewHolder = new ViewHolder(view);
    //注册子项点击事件
        viewHolder.fruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = viewHolder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clicked view "+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        }
    );
    //注册子项中的控件的点击事件
        viewHolder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = viewHolder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clicked image "+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        }
    );
        return viewHolder;
    }
    

    不得不说RecyclerView确实比ListView强大。

    相关文章

      网友评论

          本文标题:《Android第一行代码》first reading 六

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