ColorPickerView 是之前一个智能家居项目实战中所写的自定义控件,主要用于取得RGB 0~255范围的值,然后转换成十六进制0~FF的值,发送给网关控制RGB彩灯。参考的是网上一个朋友的源码写的,多的不说了,先看效果图
activity_mian.xml文件:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/tv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/ll_color"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:text="颜色取值" />
android:id="@+id/ll_color"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical">
MainActivity.java文件
package zxz.colorpickerdemo;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import zxz.colorpickerdemo.view.ColorPickerView;
public class MainActivity extends AppCompatActivity {
private LinearLayout ll;
private TextView tv;
private ColorPickerView colorPickerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.ll_color);
tv = (TextView) findViewById(R.id.tv_info);
colorPickerView = new ColorPickerView(this);
ll.addView(colorPickerView);
colorPickerView.setOnColorBackListener(new ColorPickerView.OnColorBackListener() {
@Override
public void onColorBack(int a, int r, int g, int b) {
tv.setText("R:" + r + "\nG:" + g + "\nB:" + b + "\n" + colorPickerView.getStrColor());
tv.setTextColor(Color.argb(a, r, g, b));
}
});
}
}
可以发现,这里自定义控件并没有直接在布局文件使用,原因是因为需要用户根据不同的需求通过自定义控件的构造函数传递给控件,所以通过ViewGroup.add()将ColorPickerView添加进去!
ColorPickerView colorPickerView = new ColorPickerView(context);
ll.addView(colorPickerView);
-核心