简体   繁体   中英

Android: ViewGroup in custom Toast

I created a custom Toast in my app and I have put in a class to call it from anywhere. It needs a ViewGroup in the findViewById . But I don't know send it when I'm in a class that extends Activity and is not an event ... thanks

Module.java

public static void toast(Context context, View view, String texto, int perfilColor, int icono) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
    View layouttoast = inflater.inflate(R.layout.toast, (ViewGroup)view.findViewById(R.id.toastcustom));
    ((TextView) layouttoast.findViewById(R.id.texttoast)).setText(Html.fromHtml(texto));

    ((ImageView) layouttoast.findViewById(R.id.imagenToast)).setImageResource(icono);
    ((LinearLayout) layouttoast.findViewById(R.id.toastcustom)).setBackgroundResource(cargarColorToast(perfilColor));

    Toast mytoast = new Toast(context);
    mytoast.setView(layouttoast);
    mytoast.setDuration(Toast.LENGTH_SHORT);
    mytoast.show();
}

MainActivity.java

...

if(...) {
    Module.toast(MainActivity.this, ¿? , "error", color, icon);
}

This is how i use a custom toast.

public class CustomToast {

    public static Toast makeToast(Activity activity, String text, int duraion ){
        LayoutInflater inflater = activity.getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_achievement, (ViewGroup) activity.findViewById(R.id.toast_layout_root));

        TextView textView = (TextView) layout.findViewById(R.id.text);
        textView.setText(text);

        Toast toast = new Toast(activity.getApplicationContext());
        toast.setDuration(duraion);
        toast.setView(layout);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }
}

and the xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_margin="10dp"
    android:padding="8dp" >

 <!-- content goes here-->

</LinearLayout>

not that the id has to be toast_layout_root or it wont work.

Basically, you don't need to pass a view along anyway.

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