我是android的新手,我想知道是否可以在onFinishInflate上添加吐司。如果这是一个愚蠢的问题,请原谅。我创建了这样的视图。
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
import android.widget.Toast;
public class CustomView extends View {
private Rect rectangle;
private Paint paint;
public CustomView(Context context) {
super(context);
int x = 50;
int y = 50;
int sideLength = 200;
// create a rectangle that we'll draw later
rectangle = new Rect(x, y, sideLength, sideLength);
// create the Paint and set its color
paint = new Paint();
paint.setColor(Color.GRAY);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawRect(rectangle, paint);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
Toast.makeText(getApplicationContext(),"onfinishinflate",Toast.LENGTH_SHORT).show();
}
}
最佳答案
更新资料
View有自己的方法,称为getContext()
,因此您可以像这样使用
Toast.makeText(getContext(), "onfinishinflate", Toast.LENGTH_SHORT).show();
Reference
private Context context;
public CustomView(Context context) {
super(context);
this.context = context;
// Rest of ur codes
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
Toast.makeText(context, "onfinishinflate", Toast.LENGTH_SHORT).show();
}
使用构造函数在类中设置上下文,并将其用于Toast用途
关于java - 如何在FinishInflate上为此 View 添加 toast ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59178677/