Android common interface controls two

A, ListView use

 ListView showing a list of content data, and can display the list screen in accordance highly adaptive.

Property Name

Functional Description

android:listSelector

When the entry is clicked, change the background color entry

android:divider

Set division line color

android:dividerHeight

Setting the height of the dividing line

android:scrollbars

Whether to display a scroll bar

android:fadingEdge

Remove the top and bottom of the black shadow

   Common data adapter (Adapter): a bridge between the data adapter and the data view that is similar to a converter, converts the user data into the complex acceptable manner rendering.

    Common data adapter BaseAdapter, SimpleAdapter, ArrayAdapter

    ①BaseAdapter suggests that it is essential adapter. He is actually an abstract class, usually inherit BaseAdapter when a custom adapter.

    BaseAdapter Methods

 

Method name
Functional Description
public int getCount()
Item Gets the total number of entries
public Object getItem(int position)
(Position) to obtain an Item object based on position
public long getItemId(int position)
(Position) that it takes a position based on the id of Item
public View getView(int position, View convertView, ViewGroup parent)
To obtain the corresponding position corresponding to Item view, position is the current position of the Item, convertView for multiplexing the old view, parent for loading XML layout.

 

②SimpleAdapter inherited from BaseAdapter, BaseAdapter implements four abstract methods and encapsulation. Therefore, when using the data SimpleAdapter adaptation only need to pass the appropriate parameters to the constructor. SimpleAdapter specific information construction method is as follows:

③ArrayAdapter also BaseAdapter subclass, usage and SimpleAdapter Similarly, developers only need to pass the appropriate parameters can be inside the constructor. ArrayAdapter commonly used to adapt the TextView control. Configuration as follows:

public ArrayAdapter(Context context,int resource);    //context上下文对象 resource Item布局的资源ID
public ArrayAdapter(Context context,int resource, int textViewResourceId);    //textViewResourceId    Item布局中相应TextView的id
public ArrayAdapter(Context context,int resource,T[] objects);    //objects    需要适配的数组类型的数据
public ArrayAdapter(Context context,int resource,int textViewResourceId,T[] objects);    
public ArrayAdapter(Context context,int resource,List<T> objects);
public ArrayAdapter(Context context,int resource,int textViewResourceId, List<T> objects)    //需要适配的List类型的数据

ListView Case:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:text="购物商城"
        android:textColor="#FFFFFF"
        android:background="#FF8F03"
        android:gravity="center"
        />
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>


</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/iv"
        android:layout_width="120dp"
        android:layout_height="90dp"
        android:layout_centerVertical="true"/>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/iv"
        android:layout_centerVertical="true">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="桌子"
            android:textSize="20sp"
            android:textColor="#000000"/>
        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="价格"
            android:textSize="20sp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/title"
            android:textColor="#FF8F03"/>
        <TextView
            android:id="@+id/price"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1000"
            android:textSize="20sp"
            android:layout_below="@+id/title"
            android:layout_toRightOf="@id/tv_price"
            android:textColor="#FF8F03"
            android:layout_marginTop="10dp"/>

    </RelativeLayout>

</RelativeLayout>

 

MainActivity.java

package com.example.listviewdemo;


import androidx.appcompat.app.AppCompatActivity;


import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import org.w3c.dom.Text;


public class MainActivity extends AppCompatActivity {
    private String[] titles = {"桌子","苹果","蛋糕","线衣","猕猴桃"};
    private String[] prices = {"1800元","10元/kg","300元","350元","10元/kg"};
    private int[] icons = {R.drawable.table,R.drawable.apple,R.drawable.cakes,R.drawable.wireclothes,R.drawable.scarf};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.lv);
        MyBaseAdapter adapter = new MyBaseAdapter();
        listView.setAdapter(adapter);
    }


    class MyBaseAdapter extends BaseAdapter{


        @Override
        public int getCount() {         //获取item总数
            return titles.length;
        }


        @Override
        public Object getItem(int i) {      //返回items的数据对象
            return titles[i];
        }


        @Override
        public long getItemId(int i) {      //返回items的id
            return i;
        }


        @Override
        public View getView(int i, View convertview, ViewGroup viewGroup) {    //返回items的view视图
            //方案一
//            //将xml转换成view对象
//            View view = View.inflate(MainActivity.this,R.layout.list_item,null);
//            //初始化view对象的控件
//            TextView title = view.findViewById(R.id.title);
//            TextView price = view.findViewById(R.id.price);
//            ImageView imageView = view.findViewById(R.id.iv);
//            title.setText(titles[i]);
//            price.setText(prices[i]);
//            imageView.setImageResource(icons[i]);
//            return view;
            ViewHolder holder;
            if(convertview == null){
                convertview = View.inflate(MainActivity.this,R.layout.list_item,null);
                holder = new ViewHolder();
                holder.title = convertview.findViewById(R.id.title);
                holder.price = convertview.findViewById(R.id.price);
                holder.iv = convertview.findViewById(R.id.iv);
                convertview.setTag(holder);
            }else{
                holder = (ViewHolder)convertview.getTag();
            }
            holder.title.setText(titles[i]);
            holder.price.setText(prices[i]);
            holder.iv.setImageResource(icons[i]);


            return convertview;
        }
    }
    class ViewHolder{
        TextView title;
        TextView price;
        ImageView iv;
    }
}

operation result:

Two, RecyclerVi ew use

RecyclerView: after Android5.0 is provided for displaying the control of large amounts of data within a limited range of the window.

 

Compared with the ListView, RecyclerView advantages are: 

  • Showing the effect of: RecyclerView control list of effects can be achieved by lateral or vertical LayoutManager class GridView cascade effect and effect, and can achieve a list ListView control effect vertical. 

  • Adapter: RecyclerView controls using RecyclerView.Adapter adapter, the adapter will BaseAdapter in getView () method split onCreateViewHolder () method and onBindViewHolder () method, mandatory use ViewHolder class, the coding standardization, avoiding the beginner to write poor performance of the code.

Compared with the ListView, RecyclerView advantages are:

  • Multiplexing effect: RecyclerView controls Item object reuse work implemented by the control themselves, and ListView control Item object reuse work needs to be operated by the developer convertView of setTag () method and getTag () method. 

  • Animation: RecyclerView controls can setItemAnimator () method animate Item, and ListView controls can not animate Item by this method.

Example:

activity_main.xml

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

recycler_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:orientation="horizontal">


    <ImageView
        android:id="@+id/iv"
        android:layout_width="120dp"
        android:layout_height="90dp"
        android:src="@drawable/siberiankusky"/>
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp">
        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="#FF8F03"
            android:text="哈士奇"/>
        <TextView
            android:id="@+id/introduce"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/name"
            android:textColor="#FF716C"
            android:minLines="2"
            android:ellipsize="end"
            android:text="西伯利亚雪橇犬,常见别名哈士奇,昵称为二哈"/>


    </RelativeLayout>


</LinearLayout>

MainActicty.java

package com.example.recyclerview;


import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;


import org.w3c.dom.Text;


public class MainActivity extends AppCompatActivity {
    private RecyclerView recycleview;
    private HomeAdapter homeAdapter;
    private String[] names = { "小猫", "哈士奇", "小黄鸭","小鹿","老虎"};
    private int[]  icons= { R.drawable.cat,R.drawable.siberiankusky,
            R.drawable.yellowduck,R.drawable.fawn, R.drawable.tiger};
    private String[] introduces = {
            "猫,属于猫科动物,分家猫、野猫,是全世界家庭中较为广泛的宠物。",
            "西伯利亚雪橇犬,常见别名哈士奇,昵称为二哈。",
            "鸭的体型相对较小,颈短,一些属的嘴要大些。腿位于身体后方,因而步态蹒跚。",
            "鹿科是哺乳纲偶蹄目下的一科动物。体型大小不等,为有角的反刍类。",
            "虎,大型猫科动物;毛色浅黄或棕黄色,满有黑色横纹;头圆、耳短,耳背面黑色,中央有一白斑甚显著;四肢健壮有力;尾粗长,具黑色环纹,尾端黑色。"
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recycleview = findViewById(R.id.recycleview);   //初始化recycleview
        recycleview.setLayoutManager(new LinearLayoutManager(this/*,LinearLayoutManager.HORIZONTAL,true*/));//设置recleview 的布局方式为线性布局默认为垂直方向
        homeAdapter = new HomeAdapter();
        recycleview.setAdapter(homeAdapter);    //设置适配器
    }


    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder>{   //自定义适配器


        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.recylcer_item,parent,false);    //将xml转换成view控件
            MyViewHolder myViewHolder = new MyViewHolder(view);     //放置在Holder中
            return myViewHolder;
        }


        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {  //给适配器绑定Holder
            holder.name.setText(names[position]);
            holder.introduce.setText(introduces[position]);
            holder.iv.setImageResource(icons[position]);
        }


        @Override
        public int getItemCount() {
            return names.length;
        }   //返回items的长度


        class MyViewHolder extends RecyclerView.ViewHolder{     //自定义holder
            TextView name;
            TextView introduce;
            ImageView iv;
            public MyViewHolder(@NonNull View itemView) {   //设置holder的变量
                super(itemView);
                name =(TextView) itemView.findViewById(R.id.name);
                introduce =(TextView) itemView.findViewById(R.id.introduce);
                iv =(ImageView) itemView.findViewById(R.id.iv);
            }
        }
        }
    }

operation result:

 

Third, the Custom View

When the control system does not meet the requirements, need custom control. The most simple custom View is to create a class that inherits from the View class or subclass, and override the constructor of the class.

public class Customview extends View{
    public Customview(Context context) {    //在Java代码中创建对象时,使用该构造函数
         super(context);
     }
     public Customview(Context context, AttributeSet attrs) {    //在XML布局中引入自定义控件时,使用该构造函数
         super(context, attrs);    
     }
 }

Because the system comes with a style or control can not meet the functional requirements, so we need to add extra style and functionality by rewriting method specified in the Custom View.

Custom View conventional three methods as follows: 

  • onMeasure () method: measurements. 

    onMeasure(int widthMeasureSpec, int heightMeasureSpec)

    Get the specified parent container widthMeasureSpec width of the control, heightMeasureSpec obtain the specified height of the parent container control

  • the onDraw () Method: draw the image. 

    canvas represents the canvas, he used with the Paint category (brush).

  • onLayout () method: specify the layout of the position of neutron control.

    onLayout(boolean changed,int left,int top,int right,int bottom) 

    Custom View representation changed the size and location has changed. left, top, right, bottom left, respectively, top, right, from the bottom of the child controls the parent container.

 

Measurement mode

  • EXACTLY: When the width and height of the custom value to a specific value when used as 100dp, width and height values ​​at this time are accurate size control. 

  • AT_MOST: When the aspect value when wrap_content custom control, in which case the width and height of the maximum value of the control value space control data content obtainable. 

  • UNSPECIFIED: Used when the parent container does not specify the width and height of the custom value.

Note: The parameter widthMeasureSpec and heightMeasureSpec are designated parent container width and height of the control, the control also needs to set a specific width and height by setMeasuredDimension (int, int) method.

 

Example:

cirecleview.java

package com.example.myapplication;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;


import androidx.annotation.Nullable;


public class circleview extends View {


    public circleview(Context context) {
        super(context);
    }


    public circleview(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //半径
        int r = getMeasuredHeight()/2;
        //圆心位置
        int centerX = getLeft() + r;
        int centerY = getTop() + r;
        Paint paint = new Paint();
        paint.setColor(Color.RED);


        //绘制
        canvas.drawCircle(centerX,centerY,r,paint);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">


    <com.example.myapplication.circleview
        android:layout_width="100dp"
        android:layout_height="100dp"
        tools:ignore="MissingConstraints" />


</RelativeLayout>

 

operation result:

Published 40 original articles · won praise 2 · Views 5161

Guess you like

Origin blog.csdn.net/Dnesity/article/details/104806737