0%

自定义 View

组合控件

https://www.jianshu.com/p/8b0c145acef2

自定义 ViewGroup

参考链接: https://developer.android.com/develop/ui/views/layout/custom-views/custom-components

自定义 View

https://blog.csdn.net/nihaomabmt/article/details/109668801

基本方法:继承已有的组件,重写方法 onDraw(), onMeasure(), onKeyDown()
进阶:继承 View, 在构造方法中获取 XML 中和动态设置的属性和参数,重写 onMeasure()onDraw() 方法

在 XML 中添加属性:

  • Define custom attributes for your view in a resource element
    在 res/values/attrs.xml 中添加
    1
    2
    3
    4
    5
    6
    7
    8
    9
    <resources>
    <declare-styleable name="PieChart">
    <attr name="showText" format="boolean" />
    <attr name="labelPosition" format="enum">
    <enum name="left" value="0"/>
    <enum name="right" value="1"/>
    </attr>
    </declare-styleable>
    </resources>
    自定义属性命名空间:http://schemas.android.com/apk/res/[your package name]
    非自定义属性命名空间:http://schemas.android.com/apk/res/android
    1
    2
    3
    4
    5
    6
    7
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto">
    <com.example.customviews.charting.PieChart
    custom:showText="true"
    custom:labelPosition="left" />
    </LinearLayout>
  • Specify values for the attributes in your XML layout
  • Retrieve attribute values at runtime
  • Apply the retrieved attribute values to your view
    pass the AttributeSet to obtainStyledAttributes(). This method passes back a TypedArray array of values that have already been dereferenced and styled.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public PieChart(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.getTheme().obtainStyledAttributes(
    attrs,
    R.styleable.PieChart,
    0, 0);

    try {
    mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
    textPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
    } finally {
    a.recycle(); // TypedArray 使用完要回收
    }
    }

在代码中动态添加属性:

1
2
3
4
5
6
7
8
9
public boolean isShowText() {
return mShowText;
}

public void setShowText(boolean showText) {
mShowText = showText;
invalidate(); // redrawn, invalidate the view after any change to its properties that might change its appearance
requestLayout(); // you need to request a new layout if a property changes that might affect the size or shape of the view
}

重写 onDraw 方法

利用 Canvas 和 Paint 对象进行绘制,Canvas 决定画什么形状,Paint 决定形状的颜色等属性。在构造方法中做这些属性的初始画,不要在 onDraw() 方法中做。

在代码中动态设置 View 宽高

1
2
3
4
5
myGraphView.setLayoutParams(new LayoutParams(width, height));

ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);