Day4 自定义控件/ListView/RecyclerView


创建自定义控件

引入布局

在新增的title.xml中创建一个自定义的标题栏:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/title_bg">

    <Button
        android:id="@+id/title_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:background="@drawable/back_bg"
        android:text="Back"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Title Text"
        android:textColor="#fff"
        android:textSize="24sp"
        />

    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:background="@drawable/edit_bg"
        android:text="Edit"
        android:textColor="#fff"
        />
</LinearLayout>

其中android:layout_margin这个属性可以指定控件在上下左右方向上偏移的距离,也可以用android:layout_marginLeftandroid:layout_marginTop等属性来单独指定偏移距离。
接下来是在activity_main.xml中使用:

<include layout="@layout/title" />

最后在MainActivity中将系统自带的标题栏隐藏掉:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null)
            actionBar.hide();
    }

创建自定义控件

如果在每一个活动中都需要重新注册一遍返回按钮的点击事件,无疑会增加很多重复代码,所以使用自定义控件的方式来解决。
新建TitleLayout继承自LinearLayout,让它成为我们自定义的标题栏控件:

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs){
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        //为两个按钮注册点击事件
        Button titleBack = (Button) findViewById(R.id.title_back);
        Button titleEdit = (Button) findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ((Activity)getContext()).finish();
            }
        });
        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"You clicked Edit button", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Tips:Difference between new View.OnClickListener and new OnClickListener:
If you’re imported View.OnClickListener, both will refer to the same class and will work identically.
View.OnClickListener is just often used to distinguish from DialogInterface.OnClickListener

我们重写了LinearLayout中带有两个参数的构造函数,在布局中引入TitleLayout控件就会调用这个构造函数。用LayoutInflater来实现对标题栏布局的动态加载,通过from()方法空空伊构建出一个LayoutInflater对象,然后调用inflate()方法就可以动态加载一个布局文件,其中第二个参数是给加载好的布局再添加一个父布局,这里我们像要指定为TitleLayout,于是直接传入this。
在布局文件中添加这个自定义控件:

    <com.example.uicustomviews.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

这样的话,每当我们在一个布局中引入TitleLayout时,返回按钮和编辑按钮的点击事件就已经自动实现好了,这就省去了很多编写重复代码的工作。


ListView

ListView是最常用的一个控件了,在xml中定义:

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

在MainActivity中使用:

    private String[] data = {"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple","Pineapple"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //构造适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
    }

数组中的数据是无法直接传递给ListView的,需要借助适配器来完成,Android中提供了很多适配器的实现类,其中我认为最好用的就是ArrayAdapter。它可以通过泛型来指定要适配的数据类型,然后在构造函数中把要适配的数据传入,其中android.R.layout.simple_list_item_1是一个Android内置的布局文件。

定制ListView界面

首先自定义类:

public class Fruit {
    private String name;
    private int imageId;
    public Fruit(String name, int imageId){
        this.name = name;
        this.imageId= imageId;
    }
    public String getName(){
        return name;
    }
    public int getImageId(){
        return imageId;
    }
}

自定义适配器:

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;
    public FruitAdapter(Context context, int textViewResourceId, List<Fruit> objects){
        //用于将上下文、ListView子项布局的id和数据都传进来
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position); //得到当前的Fruit实例
        //为这个子项加载我们传入的布局,false表示只让我们在父布局中声明的layout属性生效,不为这个View添加父布局,因为一旦View有了父布局之后,它就不能再添加到ListView中了。
        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false );
        ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image); //获取ImageView实例
        TextView fruitName = (TextView) view.findViewById(R.id.fruit_name); //获取Textview实例
        fruitImage.setImageResource(fruit.getImageId());
        fruitName.setText(fruit.getName());
        return view;
    }
}

最后在MainActivity中使用:

    private List<Fruit> fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();   //初始化水果数据
        //构造adapter对象
        FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);   //设定ListView
    }

提升ListView的运行效率

目前我们ListView的运行效率是很低的,因为在FruitAdapter的getView()方法中,每次都将布局重新加载了一遍。
getView()方法中还有一个convertView参数,这个参数用于将之前加载好的布局进行缓存,以便之后可以进行重用。修改代码后:

        View view;
        if(convertView == null)
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        else
            view = convertView;

这样就大大提高了ListView的运行效率。继续优化:在getView()方法中还是会调用View的findViewById()方法来获取一次控件的实例。可以借助一个ViewHolder来对这部分性能进行优化,修改代码:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView == null) {
            view = LayoutInflater.from(getContext()).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;
    }

    class ViewHolder {
        ImageView fruitImage;
        TextView fruitName;
    }

我们新增了一个内部类ViewHolder,用于对控件的实例进行缓存。把控件的实例都放在ViewHolder里,然后调用setTag()的方法,将ViewHolder对象存储在View中。当convertView不为null的时候,则调用View的getTag()方法,把ViewHolder重新取出。这样就不用每次通过findViewById()方法来获取控件实例了。

ListView的点击事件

在MainActivity中添加点击监听器即可:

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fruit fruit = fruitList.get(position);
            Toast.makeText(MainActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();
        }
    });

RecyclerView

RecyclerView同百分比布局,定义在了support库当中,首先需要在项目的build.gradle中添加相应的依赖库才行:

compile 'com.android.support:recyclerview-v7:24.2.1'

然后在xml中修改代码:

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

为RecyclerView准备一个适配器:

//适配器继承自RecyclerView.Adapter并将泛型指定为FruitAdapter.ViewHolder(ViewHolder我们定义的是内部类)
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private List<Fruit> mFruitList;
    //定义内部类ViewHolder,继承自RecyclerView.ViewHolder
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;
        //构造函数中传入一个View参数,通常是RecyclerView子项最外层布局
        public ViewHolder(View view){
            super(view);
            //获取布局中的实例
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruit_name);
        }
    }
    //用于把要展示的数据源传进来,并赋值给一个全局变量mFruitList
    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }
    //由于FruitAdapter是继承自RecyclerView.Adapter的,那么就要重写以下3个方法

    @Override
    //将fruit_item布局加载进来,然后创建一个ViewHolder实例,并把加载出来的布局传入到构造函数当中
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    //用于对RecyclerView子项的数据进行赋值,会在每个子项被滚动到屏幕内的时候执行,这里通过position参数得到当前的Fruit实例
    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();
    }
}

准备好适配器后,就可以开始使用RecyclerView了,修改MainActivity中的代码:

    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits(); //初始化水果数据
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        //LayoutManager用于指定RecyclerView的布局方式,这里是线性布局的意思,可以实现和ListView类似的效果。
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

小结:个人感觉难点还是在于如何自己构建适配器,已经很晚了,最近有考试,今后再慢慢钻研吧!一起加油。

posted @ 2016-12-15 00:35  冰芒  阅读(207)  评论(0编辑  收藏  举报