Android自定义控件可以有三种实现方式
- 组合原生控件
- 自己绘制控件
- 继承原生控件
1 组合原生控件
1.1 组合原生控件原理
组合原生控件就是将原生控件组合,然后封装到一个自定义的ViewGroup中,然后将这个ViewGroup作为一个控件使用。
例如自己写一个头部导航控件:
- 首先创建一个布局文件header_view.xml,该布局文件中的根布局是一个RelativeLayout,它有三个子布局,一个ImageVeiw和两个TextView。
- 创建一个自定义的View,例子里叫HeadView,继承自RelativeLayout
- 然后通过LayoutInflater方法加载header_view布局,然后再HeadView里面执行相应控件的操作。
如此就将三个控件封装到了HeadView中,使用头部导航控件时就可以直接调用HeadView就行了。
1.2 源码实现
- 创建一个头部布局header_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#50e7ab"
android:padding="10dp">
<ImageView
android:id="@+id/back"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="@mipmap/back" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="首页"
android:textSize="17sp"
android:textColor="#ffffff" />
<TextView
android:id="@+id/right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置"
android:textSize="17sp"
android:textColor="#ffffff"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
- 创建一个HeadView
package com.example.widgetdefine;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class HeadView extends RelativeLayout {
private ImageView back;
private TextView title;
private TextView right;
public HeadView(Context context) {
super(context);
}
public HeadView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.header_view,this);
back = findViewById(R.id.back);
title = findViewById(R.id.title);
right = findViewById(R.id.right);
}
public HeadView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setOnClickBack(OnClickListener listener){
back.setOnClickListener(listener);
}
public void setTitle(String title){
this.title.setText(title);
}
public void setOnClickRight(OnClickListener listener){
right.setOnClickListener(listener);
}
public void setRight(String right){
this.right.setText(right);
}
}
- activity_main.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:orientation="vertical"
>
<com.example.widgetdefine.HeadView
android:id="@+id/header_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></com.example.widgetdefine.HeadView>
</LinearLayout>
- MainActivity调用
package com.example.widgetdefine;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private HeadView headerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
headerView = findViewById(R.id.header_view);
headerView.setOnClickBack(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"点击了返回",Toast.LENGTH_SHORT).show();
}
});
headerView.setTitle("重新设置头部");
headerView.setRight("设置右侧标题");
}
}
1.3 运行截图
图1.1 组合原生控件实例运行截图2 自己绘制控件
2.1 自己绘制控件原理
根据需要,可能需要重写以下三个方法:
- onMeasure():测量自己的大小,为正式布局提供意见(注意,只是建议,至于用不用,要看onLayout);
- onLayout():使用layout()函数对所有子控件布局,如果自定义控件继承的是View,它可以不重写onLayout();如果是ViewGroup,则子类必须重写,因为在ViewGroup中,onLayout是个抽象方法
- onDraw():根据布局位置绘图
关于View的绘制原理,可以参考文章【Android】View绘制流程
在ViewGroup中,onLayout源码如下
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
在View中,onLayout源码如下:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
2.2 源码实现
- 创建一个CustomButtom控件
package com.example.widgetdefine;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class CustomButton extends View implements View.OnClickListener {
private Paint mPaint;
private Rect mRect;
private Context context;
private String text;
public CustomButton(Context context) {
super(context);
}
public CustomButton(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRect = new Rect();
setOnClickListener(this);
}
public CustomButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(Color.BLUE);
canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(dip2px(context,14));
mPaint.getTextBounds(getText(),0,getText().length(),mRect);
float textWidth = mRect.width();
float textHeight = mRect.height();
Log.e("测试",getHeight()+";"+getWidth()+";"+textWidth+";"+textHeight);
canvas.drawText(getText(),getWidth()/2-textWidth/2,getHeight()/2+textHeight/2,mPaint);
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
@Override
public void onClick(View v) {
Toast.makeText(context,"测试",Toast.LENGTH_SHORT).show();
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
- activity_main.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:orientation="vertical"
>
<com.example.widgetdefine.CustomButton
android:id="@+id/custom_btn"
android:layout_width="match_parent"
android:layout_height="40dp" />
</LinearLayout>
- MainActivity调用
package com.example.widgetdefine;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
CustomButton customButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customButton = findViewById(R.id.custom_btn);
customButton.setText("按钮");
}
}
2.3 运行截图
图2.1 绘制控件截图3 继承原生控件
继承原生控件就是自定义的控件是继承android自带的控件,然后根据自己的需求更改内容,以下是一个自定义文字水平居中的TextView控件。
3.1 源码实现
- 自定义一个CenterTextView类继承自TextView
package com.example.widgetdefine;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;
@SuppressLint("AppCompatCustomView")
public class CenterTextView extends TextView {
private StaticLayout mStaticLayout;
private TextPaint mTextPaint;
public CenterTextView(Context context) {
super(context);
}
public CenterTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
initView();
}
private void initView() {
if (mTextPaint == null) {
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
}
mTextPaint.setTextSize(getTextSize());
mTextPaint.setColor(getCurrentTextColor());
mStaticLayout = new StaticLayout(getText(), mTextPaint, getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
}
@Override
protected void onDraw(Canvas canvas) {
mStaticLayout.draw(canvas);
}
@Override
public void setShadowLayer(float radius, float dx, float dy, int color) {
super.setShadowLayer(radius, dx, dy, color);
if (mTextPaint == null) {
mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
}
mTextPaint.setShadowLayer(radius, dx, dy, color);
}
}
- activity_main.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:orientation="vertical"
>
<com.example.widgetdefine.CenterTextView
android:id="@+id/text_view"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
- MainActivity调用
package com.example.widgetdefine;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
CenterTextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("测试");
}
}
网友评论