gpt4 book ai didi

java - 在android中制作一个自定义函数,这样我就可以在任何地方使用它

转载 作者:行者123 更新时间:2023-12-01 21:55:46 25 4
gpt4 key购买 nike

我创建了一个java类,但我认为如果它不是用于getLayoutInflator()getApplicationContext(),这会起作用我该如何解决这个问题,这就是我所拥有的

public final class CustomFunctions {
/**
* Private constructor to prevent instantiation
*/
private CustomFunctions() {}

public static void customToast(String msg){
/*Custom Toast Message*/
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_layout_root));


TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(msg);
Button btnDismiss = (Button) layout.findViewById(R.id.btndismiss);
final Toast toast = new Toast(getApplicationContext());


toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
hideDialog();
btnDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toast.cancel();
}
});
/*Custom Toast Message*/
}
}

最佳答案

如果我很好地理解你的问题,你确实需要将上下文作为参数传递给类或函数。这就是你可以这样调用它

CustomFunctions.customToast(getApplicationContext(),"This is Toast message");


public final class CustomFunctions {
/**
* Private constructor to prevent instantiation
*/
private CustomFunctions() {}

public static void customToast(Context context,String msg){
/*Custom Toast Message*/
LayoutInflater inflater = LayoutInflater.from(context);**//get inflater service from context**
View layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_layout_root));


TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(msg);
Button btnDismiss = (Button) layout.findViewById(R.id.btndismiss);
final Toast toast = new Toast(context);**//pass context**


toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
hideDialog();
btnDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toast.cancel();
}
});
/*Custom Toast Message*/
}

}

关于java - 在android中制作一个自定义函数,这样我就可以在任何地方使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743164/

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