【问题标题】:Customview like Toast像 Toast 一样的自定义视图
【发布时间】:2017-11-30 14:34:49
【问题描述】:

我有一个自定义视图。我想在 android 中像吐司一样显示 customview。

Toast.makeText(getApplicationContext(),"text",Toast.LENGTH_LONG).show()

也就是说,我希望我的自定义视图通过更改文本等基本属性显示在应用程序的任何位置(应用程序内的全局)。

请指点我正确的方向。

请注意:我不想使用 addView() 和 removeView() 来添加和删除自定义视图。在我的情况下,自定义 Toast 也不起作用,因为我需要使用这个 customview。

【问题讨论】:

标签: android android-custom-view


【解决方案1】:

很简单,你可以通过扩展 Toast 类来做到这一点

假设我的自定义 Toast 类是 NexoolCustomToast,它扩展了 Toast 类。下面是自定义 Toast 类的代码。

   import android.app.Activity;
   import android.app.Application;
   import android.content.Context;
   import android.view.Gravity;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.widget.TextView;
   import android.widget.Toast;

   /**
    * Created by Abhishek on 24-03-2017.
    */

   /**
    * By Default shows Error i.e. Fail toast
    * */
   public class NexoolCustomToast extends Toast {

       private Context mContext;

       private View mView;

       private LayoutInflater mLayoutInflater;

       private TextView mTitleTextView, mMessageTextView;

       /**
        * Construct an empty Toast object.  You must call {@link #setView} before you
        * can call {@link #show}.
        *
        * @param context The context to use.  Usually your {@link Application}
        *                or {@link Activity} object.
        */
       public NexoolCustomToast(Context context) {
           super(context);
           mContext = context;
           mLayoutInflater = LayoutInflater.from(context);
           mView = mLayoutInflater.inflate(R.layout.nexool_fail_custom_toast, null);
           initialiseView(mView);
           setView(mView);
           setGravity(Gravity.TOP | Gravity.END, 0, 0);
       }

       public NexoolCustomToast(Context context, boolean state) {
           super(context);
           mContext = context;
           mLayoutInflater = LayoutInflater.from(context);
           if (state) {
               mView = mLayoutInflater.inflate(R.layout.nexool_success_custom_toast, null);
           } else {
               mView = mLayoutInflater.inflate(R.layout.nexool_fail_custom_toast, null);
           }
           initialiseView(mView);
           setView(mView);
           setGravity(Gravity.TOP | Gravity.END, 0, 0);
       }

       private void initialiseView(View mView) {

           mTitleTextView = (TextView) mView.findViewById(R.id.titleTextView);

           mMessageTextView = (TextView) mView.findViewById(R.id.messageTextView);

       }

       public void setTitle(String title) {

           if (title != null && title.length() != 0) {

               mTitleTextView.setText(title);

           } else {

               mTitleTextView.setVisibility(View.GONE);

           }

       }

       public void setMessage(String message) {

           if (message != null && message.length() != 0) {

               mMessageTextView.setText(message);

           } else {

               mMessageTextView.setVisibility(View.GONE);

           }

       }

       @Override
       public void show() {
           super.show();
       }

       @Override
       public void cancel() {
           super.cancel();
       }

       public static NexoolCustomToast makeText(Context mContext, String mTitle, String mMessage) {
           NexoolCustomToast mNexoolCustomToast = new NexoolCustomToast(mContext);

           mNexoolCustomToast.setTitle(mTitle);

           mNexoolCustomToast.setMessage(mMessage);

           return mNexoolCustomToast;
       }

       public static NexoolCustomToast makeText(Context mContext, String mTitle, String mMessage, boolean state) {
           NexoolCustomToast mNexoolCustomToast = new NexoolCustomToast(mContext, state);

           mNexoolCustomToast.setTitle(mTitle);

           mNexoolCustomToast.setMessage(mMessage);

           return mNexoolCustomToast;
       }
   }

在本课程中,我使用了来自 nexool_fail_custom_toast.xml、nexool_success_custom_toast.xml 的 xml 布局,具有四种布局屏幕尺寸(layout-large、layout-normal、layout-small、layout-xlarge)。

      //layout-large/nexool_fail_custom_toast.xml
      <?xml version="1.0" encoding="utf-8"?>
      <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:background="@android:color/white"
                android:layout_alignParentEnd="true"
                android:layout_marginTop="?android:attr/actionBarSize"
                android:layout_marginBottom="15dp"
                android:layout_marginRight="15dp"
                android:elevation="5dp">

                <ImageButton
                    android:id="@+id/cancelToastImageButton"
                    android:layout_width="25dp"
                    android:layout_height="match_parent"
                    android:background="@android:color/holo_red_dark"
                    android:scaleType="centerInside"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:padding="15dp">

                    <TextView
                        android:id="@+id/titleTextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Error Title"
                        android:minWidth="300sp"
                        android:textColor="@android:color/holo_red_dark"
                        android:textAppearance="?android:attr/textAppearanceMedium" />

                    <TextView
                        android:id="@+id/messageTextView"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Error Message"
                        android:minWidth="300sp"
                        android:paddingTop="10dp"
                        android:textColor="@android:color/black"
                        android:textAppearance="?android:attr/textAppearanceSmall"/>

                </LinearLayout>


            </LinearLayout>

        </RelativeLayout>







       //layout-large/nexool_success_custom_toast.xml
       <?xml version="1.0" encoding="utf-8"?>
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:background="@android:color/transparent">

           <LinearLayout
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:orientation="horizontal"
               android:background="@android:color/white"
               android:layout_alignParentEnd="true"
               android:layout_marginTop="?android:attr/actionBarSize"
               android:layout_marginBottom="15dp"
               android:layout_marginRight="15dp"
               android:elevation="5dp">

               <ImageButton
                   android:id="@+id/cancelToastImageButton"
                   android:layout_width="25dp"
                   android:layout_height="match_parent"
                   android:background="@android:color/holo_green_light"
                   android:scaleType="centerInside"/>

               <LinearLayout
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:orientation="vertical"
                   android:padding="15dp">

                   <TextView
                       android:id="@+id/titleTextView"
                       android:layout_width="match_parent"
                       android:layout_height="wrap_content"
                       android:text="Error Title"
                       android:minWidth="300sp"
                       android:textColor="@android:color/holo_green_light"
                       android:textAppearance="?android:attr/textAppearanceMedium" />

                   <TextView
                       android:id="@+id/messageTextView"
                       android:layout_width="match_parent"
                       android:layout_height="wrap_content"
                       android:text="Error Message"
                       android:minWidth="300sp"
                       android:paddingTop="10dp"
                       android:textColor="@android:color/black"
                       android:textAppearance="?android:attr/textAppearanceSmall"/>

               </LinearLayout>


               </LinearLayout>

               </RelativeLayout>

现在,通过更改这些文件中视图的文本大小或宽度和高度,为 layout-small、layout-normal、layout-xlarge 制作上述两个 xml 文件。

** 如何使用 **

绿色成功布局

    NexoolCustomToast.makeText(mContext, "Success", "Success Message", true).show();

对于红色故障布局

    NexoolCustomToast.makeText(mContext, "Fail", "Fail Message", false).show();

    //OR

    NexoolCustomToast.makeText(mContext, "Fail", "Fail Message").show();

【讨论】:

  • 我想用ondraw..有没有我能做到的??
  • 是的,您可以使用 onDraw 创建 CustomView 而不是像 toast 这样的结构。 Android Toast 将为您提供时间实例的烘烤消息的优势,如果您想使用 onDraw,那么您还必须开发该逻辑。
【解决方案2】:

你可以自己定制toast,方法会带文本和show.看看。

public void showToast(String msg) {

        LayoutInflater li = getLayoutInflater();
        View layout = li.inflate(R.layout.custom_toast,
        (ViewGroup) findViewById(R.id.custom_toast_layout));
        TextView toastmsg = (TextView) layout.findViewById(R.id.custom_toast_message);
        toastmsg.setText(msg);
        Toast toast = new Toast(this);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setView(layout);
        toast.show();


    }

custom_toast_message.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/custom_toast_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/toast_bg"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/custom_toast_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="Custom Toast"
            android:padding="15dp"
            android:src="@drawable/icon_toast_alert" />

        <TextView
            android:id="@+id/custom_toast_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="Custom Toast"
            android:padding="15dp"
            android:text="Custom Toast"
            android:textAlignment="center"
            android:textColor="@color/colorWhite"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>

自定义吐司看起来像这样:

编码愉快!!

【讨论】:

    【解决方案3】:

    在 Common.java 文件中创建通用方法。

    public static void displayCustomToast(Activity activity, String message, String length) {
    
        // if you want to set typeface for toast text then use this //
        Typeface tfShruti = Typeface.createFromAsset(activity.getAssets(), "fonts/shruti.ttf");
    
        LayoutInflater inflater = activity.getLayoutInflater();
    
        View layout = inflater.inflate(R.layout.custom_layout,
                (ViewGroup) activity.findViewById(R.id.custom_toast_layout_id));
        // set a message
        TextView text = (TextView) layout.findViewById(R.id.tv_toast);
        text.setText(message);
        text.setTypeface(tfShruti);
    
        // Toast...
        Toast toast = new Toast(activity.getApplicationContext());
        toast.setGravity(Gravity.BOTTOM, 0, 0);
        //toast.setMargin(0,10);
        //toast.setGravity(Gravity.TOP | Gravity.LEFT, 40, 60);
        //toast.setDuration(Toast.LENGTH_LONG);
    
        if (length.equalsIgnoreCase("short")) {
            toast.setDuration(Toast.LENGTH_SHORT);
        } else {
            toast.setDuration(Toast.LENGTH_LONG);
        }
        toast.setView(layout);
        toast.show();
    }
    

    像这样创建布局。

    custom_layout.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/custom_toast_layout_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/rectangle_fill_black_color"
        android:orientation="vertical"
        android:padding="5dp">
    
        <TextView
            android:id="@+id/tv_toast"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello"
            android:textColor="#ffffff"
            android:textSize="17sp" />
    
    
    </LinearLayout>
    

    然后在这样的项目中的任何地方使用此方法。

     Common.displayCustomToast(activity, message, "long"); 
    

     Common.displayCustomToast(activity, context.getResources().getString(R.string.please_check_internet), "short");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 2021-12-27
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多