简体   繁体   中英

make a custom function in android so that i can use it every where

i made a java class but i think this would work if it wasnt for getLayoutInflator() and getApplicationContext() how can i solve this this is what i have

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

If I well understood your question, you do need to pass context as argument to the class or function. This is how you can call it

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM