遇到自定义控件的时候很苦恼、不知道从哪里下手、鄙人也是新手、记录下开发的思路
我们有时候需要把某一个功能封装成控件、很简单、写好布局、将其inflate出来
必要的属性、就跟普通的activity一样定义即可、context直接调用getContext();
public class DanmakuChannel extends RelativeLayout {
public boolean isRunning = false;
public DanmakuEntity mEntity;
private DanmakuActionInter danAction;
public DanmakuActionInter getDanAction() {
return danAction;
}
public void setDanAction(DanmakuActionInter danAction) {
this.danAction = danAction;
}
public DanmakuChannel(Context context) {
super(context);
init();
}
public DanmakuChannel(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DanmakuChannel(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public DanmakuChannel(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.danmaku_channel_layout, null);
}
}
定义完了、在布局中调用即可
<com.just.sun.widget.danmu.DanmuBase.DanmakuChannel
android:id="@+id/danA"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginTop="10dp" />
要处理点击事件、很简单、可以findViewById setOnclickListener、跟Activity是一样的、
如果更麻烦一点要捕获触摸事件、需要重写方法
下面我通过点击做了个小动画、点击屏幕会出现晃动的小手、然后消失
public View.OnTouchListener onLightTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (model.liveEntity != null) {
float x = event.getX();
float y = event.getY();
final int action = MotionEventCompat.getActionMasked(event);
switch (action) {
case MotionEvent.ACTION_DOWN://单点触摸动作