【问题标题】:make a custom function in android so that i can use it every where在android中制作一个自定义函数,以便我可以在任何地方使用它
【发布时间】:2019-11-07 06:32:49
【问题描述】:

我创建了一个 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*/
    }
}

【问题讨论】:

  • 只需将上下文传递给类,您就可以使用getLayoutInflatorgetApplicationContext

标签: java android oop


【解决方案1】:

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

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*/
}

}

【讨论】:

  • 这很好,但findViewById 仍然是红色错误消息是can not resolve method findviewbyid
  • 将视图组作为参数传递给与上下文相同的函数。 ViewGroup viewGroup = (ViewGroup) findViewById(R.id.toast_layout_root);然后调用 customToast(context,viewgroup,"YOUR MSG");
  • 检查 Snakbar 可能你需要这个material.io/develop/android/components/snackbar
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多