我正在創建一個自定義視圖。這基本上是一個帶邊框的矩形框。我希望邊框可以改變顏色,並在用戶點擊時使其可以聚焦。如果矩形失去焦點,我想讓邊框恢復原來的顏色。我想用這個背景作爲表單背景。我已經嘗試過android文檔和堆棧溢出的答案,我無法做到這一點。我讓它變得可點擊,但我無法繼續進行下去。如何使您的自定義視圖可以調焦?
public class FormBackgroundView extends View implements View.OnClickListener{
private int _borderColor;
Paint fillPaint, strokePaint;
Canvas canvas;
public FormBackgroundView(Context context) {
super(context);
init();
}
public FormBackgroundView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public FormBackgroundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public FormBackgroundView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init(){
super.setOnClickListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
fillPaint = new Paint();
strokePaint = new Paint();
fillPaint.setStyle(Paint.Style.FILL);
fillPaint.setColor(Color.WHITE);
strokePaint.setStyle(Paint.Style.FILL);
strokePaint.setColor(Color.BLACK);
strokePaint.setAntiAlias(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
canvas.drawRoundRect(0,0,getWidth(),getHeight(), 10, 10, strokePaint);
canvas.drawRoundRect(0 + 3,0 + 3,getWidth() - 3,getHeight() - 3, 7, 7, fillPaint);
} else {
canvas.drawRect(0,0,getWidth(),getHeight(), strokePaint);
canvas.drawRect(0 + 4,0 + 4,getWidth() -4 ,getHeight() -4, fillPaint);
}
this.canvas = canvas;
}
@Override
public void onClick(View view) {
}
}
的[自定義視圖不響應觸摸可能的複製](https://stackoverflow.com/questions/10406354/custom-view-not - 對應於觸摸) – Danieboy