gpt4 book ai didi

java - 如何在FinishInflate 上向该 View 添加 toast

转载 作者:行者123 更新时间:2023-12-01 19:40:14 25 4
gpt4 key购买 nike

我是 Android 新手,我想知道是否可以在 FinishInflate 上添加 toast。如果这是一个愚蠢的问题,请原谅我。我创建了一个这样的 View 。

    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/

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