gpt4 book ai didi

android - 如何使 View 对点击使用react

转载 作者:行者123 更新时间:2023-11-29 00:47:27 26 4
gpt4 key购买 nike

我已经创建了继承 View 的自定义小部件。

<com.test.www.view.ElementView
android:id="@+id/surface1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_weight="1"

/

>

public class ElementView extends View {
private final int width=100;
private final int height=100;
private Paint paint=null;
private Canvas canvas=null;

public ElementView(Context context) {
super(context);
paint = new Paint();
}

public ElementView(Context context, AttributeSet attr) {
super(context, attr);
paint = new Paint();
}


public ElementView(Context context, AttributeSet attr, int defaultStyles) {
super(context, attr, defaultStyles);
paint = new Paint();
}

@Override
protected void onMeasure(int widthSpec, int heightSpec) {
int measuredWidth = MeasureSpec.getSize(widthSpec);
int measuredHeight = MeasureSpec.getSize(heightSpec);
setMeasuredDimension(this.width,this.height);

}

@Override
protected void onDraw(Canvas canvas) {
this.canvas=canvas;
// get the size of your control based on last call to onMeasure
int height = getMeasuredHeight();
int width = getMeasuredWidth();

// Now create a paint brush to draw your widget

paint.setColor(Color.GREEN);

//define border
this.canvas.drawLine(0, 0, 0, 99, paint);
this.canvas.drawLine(0, 0, 99,0, paint);
this.canvas.drawLine(99, 0, 99, 99, paint);
this.canvas.drawLine(0, 99, 99,99, paint);

//define cells
this.canvas.drawLine(0,50,99,50,paint);
this.canvas.drawLine(30,0,30,50,paint);

//draw green rectangle
this.canvas.drawRect(new Rect(0,0,50,50),paint);
//draw some text
paint.setTextSize(8);
paint.setColor(Color.RED);
String displayText = "test";


Float textWidth = paint.measureText(displayText);

int px = width / 2;
int py = height / 2;
this.canvas.drawText(displayText, px - textWidth / 2, py, paint);
}

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
paint.setColor(Color.RED);
//change color of first cell
canvas.drawRect(new Rect(0,0,50,50),paint);
return super.dispatchTouchEvent(event);
}

}

问题是这个 ElementView 在点击时没有反应。我已经覆盖了调度事件但它没有进来。任何人都可以帮助我吗?如何使此 ElementView 对点击使用react?

最佳答案

我可能会做这样的事情:

ElementView ev = (ElementView)findViewById(R.id.surface1);
ev.setOnClickListener(evOnClick);

public OnClickListener evOnClick = new OnClickListener() {
@Override
public void onClick(View v, int arg1) {
//DO ONCLICK STUFF
}
};

我不确定您是否真的可以像您尝试的那样将 onClick 放在 View 定义中,但我希望有人能告诉我如何做。

关于android - 如何使 View 对点击使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5558368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com