开发者

How to Customise Toast in Android?

Is it possible to make Customize Toast in Android. like if can we place in it image开发者_如何学Python icon and place button.


You can also use the regular makeText() and handle the getView() to set an image next to see the next.

Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
TextView tv = (TextView) toast.getView().findViewById(android.R.id.message);
if (null!=tv) {
    tv.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
    tv.setCompoundDrawablePadding(context.getResources().getDimensionPixelSize(R.dimen.padding_toast));


You can put any view in a Toast using setView. However, I'm not quite sure why you would want to place a button in it, as a Toast will rapidly disappear. Taken from the officiel developer site :

When the view is shown to the user, appears as a floating view over the application. It will never receive focus. The user will probably be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the information you want them to see.

So the toast should only be used to display information. For more complex interactions, you can use a Dialog.


Toast is non focus able.Adding button did not make sense. However you can display information.You can also control its visibility means u can hide and show by making few changes in Toast class.


XML FILE

enter code here`<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/toast_layout_root"
          android:orientation="horizontal"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="8dp"
          android:background="#DAAA"
          >
<ImageView android:src="@drawable/droid"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_marginRight="8dp"
           />
<TextView android:id="@+id/text"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          />

'

JAVA CODE

 LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
                               (ViewGroup) findViewById(R.id.toast_layout_root));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜