Three Ways for Android to Implement Custom View

Keywords: Android xml encoding Java

About Android's customized View, I will summarize them into three types, namely self-drawing components, composite controls, inheritance controls. Next, I will give you a concrete analysis of the implementation process of these three kinds of customized View with examples.

(1) Self-drawing components

I personally understand that this is really a custom component. The View inside is drawn entirely through its own onDrwa method. The following example is a custom View drawing attempt, which can change the View background when the user clicks.

/**
 * owner-draw
 * Created by xiedong on 2017/3/10.
 */

public class MyOwnView extends View implements View.OnClickListener{

    private Paint mPaint;
    private Rect mRect;
    private int colors []={Color.RED,Color.BLUE,Color.GREEN};
    private int i=0;

    public MyOwnView(Context context) {
        super(context);

        initView();
    }

    public MyOwnView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView();
    }

    public MyOwnView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initView();
    }

    private void initView() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRect = new Rect();
        setOnClickListener(this);  //Achieve your own click events
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        mPaint.setColor(colors[i%colors.length]);
        canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);


        float textWidth = mRect.width();
        float textHeight = mRect.height();
        mPaint.setColor(Color.WHITE);
        mPaint.setTextSize(30);
        canvas.drawText("Click on Variable Colors",getWidth()/4, getHeight()/2 + textHeight/2,mPaint);
    }

    @Override
    public void onClick(View v) {

        i++;
        invalidate(); //Notify redrawing layout
    }
}
In the layout, reference is made to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_my_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.project.view.MyViewActivity">

    <com.example.project.view.MyOwnView
        android:layout_gravity="center"
        android:layout_width="180dp"
        android:layout_height="180dp" />
</LinearLayout>


This custom View is also relatively simple to use, because there is not much logic implementation, it can be used in xml files, or in java code, new

(2) Composite Control

As the name implies, some controls are combined to redefine View, which is convenient for reuse of View. I posted a case of TitleBar using composite controls.

The layout file is as follows:

<?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="40dp"
    android:orientation="horizontal"
    android:background="#440000ff"
    >
<ImageView
    android:id="@+id/title_btn"
    android:layout_width="70dp"
    android:layout_height="match_parent"
    android:src="@android:drawable/arrow_down_float"
    />
    <TextView
        android:id="@+id/title_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="20sp"
        android:gravity="center"
        android:text="Title"
        />
</LinearLayout>

Customize VIew's java code:
/**
 * Complete Custom View with Combination
 * Created by xiedong on 2017/3/10.
 */

public class TitleView extends LinearLayout{
    private ImageView titleBtn;
    private TextView titleText;
    private Context mContext;

    public TitleView(Context context) {
        super(context);
        this.mContext = context;
        initView();
    }

    public TitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    public TitleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
    }



    private void initView() {

//        View view = View.inflate(mContext,R.layout.titleview_layout,this);
        LayoutInflater.from(mContext).inflate(R.layout.titleview_layout,this);

        titleBtn = (ImageView) findViewById(R.id.title_btn);
        titleText = (TextView) findViewById(R.id.title_text);
    }


    /**
     * Set the top left arrow to listen for events
     * @param listener
     */
    public void setLeftButtonListener(OnClickListener listener){
        titleBtn.setOnClickListener(listener);
    }


    //Set title
    public void setTitleText(String title){
        titleText.setText(title);
    }
}

Set the click event of the custom view and the title in the function code

 title = (TitleView) findViewById(R.id.title);
        title.setLeftButtonListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("-------------The button is clicked————————————");
            }
        });

        title.setTitleText("custom TitleBar");


(3) Inheritance Control

This way is to inherit the existing controls and realize its own unique new functions on the basis of retaining the original functions.

/**
 * Created by xiedong on 2017/3/10.
 */

public class MyButton extends Button {

    private Context mContext;

    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;  //  Receiving context parameters

    }

    public MyButton(Context context) {
        super(context);
        this.mContext = context;
    }

    public MyButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;

    }



    private MyOnClickListener listener;
    public void setMyOnClickListener(MyOnClickListener listener){
        this.listener = listener;
    }
    public interface MyOnClickListener{
        void myClick( );
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(event.getAction()==MotionEvent.ACTION_DOWN) {   //Register Click Events when User Click Event is Down
            listener.myClick();
        }
        return true;

    }
}


Layout code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.project.MainActivity">

    


    <com.example.project.view.MyButton
        android:id="@+id/my_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ed_content" />

  

   
</RelativeLayout>

Use this custom View

mButton = (MyButton) findViewById(R.id.my_btn);
        mButton.setMyOnClickListener(new MyButton.MyOnClickListener() {
            @Override
            public void myClick() {

                System.out.println("_------------d---------");

            }
        });



Posted by zoidberg on Mon, 15 Apr 2019 09:57:32 -0700