Java 在android中创建一个自定义函数,这样我就可以随时随地使用它
我创建了一个java类,但我认为如果不是针对Java 在android中创建一个自定义函数,这样我就可以随时随地使用它,java,android,oop,Java,Android,Oop,我创建了一个java类,但我认为如果不是针对getLayoutInflator()和getApplicationContext() 我该怎么解决这是我的问题 public final class CustomFunctions { /** * Private constructor to prevent instantiation */ private CustomFunctions() {} public static void customToa
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*/
}
}只需将上下文传递给类,就可以使用
getLayoutInflator
和getApplicationContext
这很好,但是findViewById
仍然是红色错误消息是无法解析方法findViewById
将viewgroup作为参数传递给与上下文相同的函数。ViewGroup ViewGroup=(ViewGroup)findViewById(R.id.toast\u layout\u root);然后调用customToast(上下文,视图组,“您的消息”);检查是否有蛇行可能是你需要的