program story

Android의 사용자 지정 토스트 : 간단한 예

inputbox 2020. 8. 11. 08:24
반응형

Android의 사용자 지정 토스트 : 간단한 예


저는 Android 프로그래밍이 처음입니다. Android에서 사용자 지정 토스트 알림을 보여주는 간단한 예는 무엇입니까?


사용자 지정 토스트의 아래 코드를 사용하십시오. 도움이 될 수 있습니다.

toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:background="#DAAA" >

    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp" />

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:textColor="#FFF" />

</LinearLayout>

MainActivity.java

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

ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! 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();

또한 아래 링크에서 사용자 지정 토스트를 확인하십시오.

아날로그 시계가있는 맞춤형 토스트

YouTube : Android Studio에서 버튼으로 사용자 지정 토스트 만들기


토스트는 짧은 시간 간격으로 메시지를 표시하기위한 것입니다. 따라서 내 이해에 따라 이미지를 추가하고 메시지 텍스트의 크기, 색상을 변경하여 사용자 정의하고 싶습니다. 그게 전부라면 별도의 레이아웃을 만들어 Toast 인스턴스로 확장 할 필요가 없습니다.

기본 Toast의보기에는 TextView메시지를 표시하기 위한가 포함되어 있습니다 . 따라서 해당 리소스 ID 참조가있는 경우 TextView이를 사용할 수 있습니다. 이를 달성하기 위해 할 수있는 작업은 다음과 같습니다.

Toast toast = Toast.makeText(this, "I am custom Toast!", Toast.LENGTH_LONG);
View toastView = toast.getView(); // This'll return the default View of the Toast.

/* And now you can get the TextView of the default View of the Toast. */
TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message);
toastMessage.setTextSize(25);
toastMessage.setTextColor(Color.RED);
toastMessage.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_fly, 0, 0, 0);
toastMessage.setGravity(Gravity.CENTER);
toastMessage.setCompoundDrawablePadding(16);
toastView.setBackgroundColor(Color.CYAN);
toast.show();

위의 코드에서 볼 수 있듯이 setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)원하는 TextView에 상대적인 위치 를 통해 TextView에 이미지를 추가 할 수 있습니다 .

최신 정보:

위의 목적을 단순화하기 위해 빌더 클래스를 작성했습니다. 링크는 다음과 같습니다 : https://gist.github.com/TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc

HowToUse.kt위의 링크를 확인하십시오 .

산출:

여기에 이미지 설명 입력


1 단계:

먼저에서 사용자 지정 알림을위한 레이아웃을 만듭니다 res/layout/custom_toast.xml.

<?xml version="1.0" encoding="utf-8"?>
<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="fill_parent"
    android:background="#FFF"
    android:orientation="horizontal"
    android:padding="5dp" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#000" />

</LinearLayout>

2 단계 : 활동 코드에서 위의 사용자 지정보기를 가져 와서 Toast에 연결합니다.

// Get your custom_toast.xml ayout
LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_layout_id));

// set a message
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Button is clicked!");

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

자세한 내용은 Android에서 사용자 지정 토스트를 만드는 방법을 참조하십시오.

http://developer.android.com/guide/topics/ui/notifiers/toasts.html


여기 링크를 참조 하십시오 . 솔루션을 찾으십시오. 그리고 시도해보십시오.

사용자 지정 토스트보기 만들기

간단한 문자 메시지로 충분하지 않은 경우 알림 메시지에 대한 사용자 지정 레이아웃을 만들 수 있습니다. 사용자 지정 레이아웃을 생성하려면 XML 또는 애플리케이션 코드에서 View 레이아웃을 정의하고 루트 View 객체를 setView (View) 메서드에 전달합니다.

예를 들어 다음 XML (toast_layout.xml로 저장 됨)을 사용하여 오른쪽 스크린 샷에 표시되는 알림의 레이아웃을 만들 수 있습니다.

<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="10dp"
            android:background="#DAAA"
>

    <ImageView android:id="@+id/image"
               android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
    />

    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
    />
</LinearLayout>

LinearLayout 요소의 ID는 "toast_layout"입니다. 다음과 같이 XML에서 레이아웃을 확장하려면이 ID를 사용해야합니다.

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

 ImageView image = (ImageView) layout.findViewById(R.id.image);
 image.setImageResource(R.drawable.android);
 TextView text = (TextView) layout.findViewById(R.id.text);
 text.setText("Hello! 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();

먼저 getLayoutInflater () (또는 getSystemService ())를 사용하여 LayoutInflater를 검색 한 다음 inflate (int, ViewGroup)을 사용하여 XML에서 레이아웃을 확장합니다. 첫 번째 매개 변수는 레이아웃 리소스 ID이고 두 번째 매개 변수는 루트보기입니다. 이 확장 된 레이아웃을 사용하여 레이아웃에서 더 많은 View 개체를 찾을 수 있으므로 이제 ImageView 및 TextView 요소의 콘텐츠를 캡처하고 정의합니다. 마지막으로 Toast (Context)를 사용하여 새 Toast를 만들고 중력 및 기간과 같은 토스트의 일부 속성을 설정합니다. 그런 다음 setView (View)를 호출하고 팽창 된 레이아웃을 전달합니다. 이제 show ()를 호출하여 사용자 정의 레이아웃으로 토스트를 표시 할 수 있습니다.

참고 : setView (View)를 사용하여 레이아웃을 정의하지 않는 한 Toast에 공용 생성자를 사용하지 마십시오. 사용할 사용자 지정 레이아웃이없는 경우 makeText (Context, int, int)를 사용하여 Toast를 만들어야합니다.


이것은 내가 사용한 것입니다

AllMethodsInOne.java

public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) {

    final Toast toast;

    if (toastLength.equals("short")) {
        toast = Toast.makeText(mAct, tText, Toast.LENGTH_SHORT);
    } else {
        toast = Toast.makeText(mAct, tText, Toast.LENGTH_LONG);
    }

    View tView = toast.getView();
    tView.setBackgroundColor(Color.parseColor("#053a4d"));
    TextView mText = (TextView) tView.findViewById(android.R.id.message);

    mText.setTypeface(applyFont(mAct));
    mText.setShadowLayer(0, 0, 0, 0);

    tView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            toast.cancel();
        }
    });
    tView.invalidate();
    if (succTypeColor.equals("red")) {
        mText.setTextColor(Color.parseColor("#debe33"));
        tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red));
        // this is to show error message
    }
    if (succTypeColor.equals("green")) {
        mText.setTextColor(Color.parseColor("#053a4d"));
        tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green));
        // this is to show success message
    }


    return toast;
}

YourFile.java

전화하는 동안 아래에 쓰십시오.

AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();

인터넷 전체에 걸친 대부분의 customtoast xml-examples는 동일한 소스를 기반으로한다고 생각합니다.

제 생각에는 매우 오래된 Android 문서입니다. fill_parent는 더 이상 사용되지 않아야합니다. xml.9.png와 함께 wrap_content를 사용하는 것을 선호합니다. 이렇게하면 제공된 소스의 크기 전체에서 toastbackground의 최소 크기를 정의 할 수 있습니다.

더 복잡한 알림이 필요한 경우 LL 대신 프레임 또는 상대 레이아웃을 사용해야합니다.

toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/points_layout"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:layout_gravity="center"
    android:gravity="center" >

 <TextView
    android:id="@+id/points_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="15dp"
    android:text="@+string/points_text"
    android:textColor="@color/Green" />

</LinearLayout>

background.xml

<?xml version="1.0" encoding="utf-8"?>
<nine-patch
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:src="@drawable/background_96"
   android:dither="true"/>

background_96은 background_96.9.png입니다.

이것은 잘 테스트되지 않았으며 힌트를 높이 평가합니다. :)


여기에서 코드를 다운로드 할 수 있습니다 .

1 단계:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCustomToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Custom Toast" />
  </RelativeLayout>

2 단계:

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

        <ImageView
            android:id="@+id/custom_toast_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"/>

        <TextView
            android:id="@+id/custom_toast_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My custom Toast Example Text" />

</LinearLayout>

3 단계 :

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private Button btnCustomToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCustomToast= (Button) findViewById(R.id.btnCustomToast);
        btnCustomToast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Find custom toast example layout file
                View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null);
                // Creating the Toast object
                Toast toast = new Toast(getApplicationContext());
                toast.setDuration(Toast.LENGTH_SHORT);

                // gravity, xOffset, yOffset
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setView(layoutValue);//setting the view of custom toast layout
                toast.show();
            }
        });
    }
}

알림을위한 맞춤 레이아웃, custom_toast.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Custom Toast"
        android:gravity="center"
        android:id="@+id/custom_toast_text"
        android:typeface="serif"
        android:textStyle="bold"
        />
</LinearLayout>

그리고 Java 메소드 (이 메소드에 토스트 메시지를 전달) :

public void toast(String message)
{
    Toast toast = new Toast(context);
    View view = LayoutInflater.from(context).inflate(R.layout.image_custom, null);
    TextView textView = (TextView) view.findViewById(R.id.custom_toast_text);
    textView.setText(message);
    toast.setView(view);
    toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.show();
}

MainActivity.java 파일에 대한 코드입니다.

package com.android_examples.com.toastbackgroundcolorchange;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {

 Button BT;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 BT = (Button)findViewById(R.id.button1);
 BT.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {

 Toast ToastMessage = Toast.makeText(getApplicationContext(),"Change Toast Background color",Toast.LENGTH_SHORT);
 View toastView = ToastMessage.getView();
 toastView.setBackgroundResource(R.layout.toast_background_color);
 ToastMessage.show();

 }
 });
 }
}

activity_main.xml 레이아웃 파일에 대한 코드입니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.android_examples.com.toastbackgroundcolorchange.MainActivity" >

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CLICK HERE TO SHOW TOAST MESSAGE WITH DIFFERENT BACKGROUND COLOR INCLUDING BORDER" />

</RelativeLayout>

res-> layout 폴더에 생성 된 toast_background_color.xml 레이아웃 파일의 코드입니다.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

 <stroke
    android:width="3dp"
    android:color="#ffffff" ></stroke>
<padding android:left="20dp" android:top="20dp"
    android:right="20dp" android:bottom="20dp" />
<corners android:radius="10dp" />
<gradient android:startColor="#ff000f"
    android:endColor="#ff0000"
    android:angle="-90"/>

</shape>

// 원하는대로 사용자 정의 또는 기본 토스트를 표시 할 수있는 사용자 정의 토스트 클래스)

public class ToastMessage {
    private Context context;
    private static ToastMessage instance;

    /**
     * @param context
     */
    private ToastMessage(Context context) {
        this.context = context;
    }

    /**
     * @param context
     * @return
     */
    public synchronized static ToastMessage getInstance(Context context) {
        if (instance == null) {
            instance = new ToastMessage(context);
        }
        return instance;
    }

    /**
     * @param message
     */
    public void showLongMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * @param message
     */
    public void showSmallMessage(String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }

    /**
     * The Toast displayed via this method will display it for short period of time
     *
     * @param message
     */
    public void showLongCustomToast(String message) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
        TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
        msgTv.setText(message);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();


    }

    /**
     * The toast displayed by this class will display it for long period of time
     *
     * @param message
     */
    public void showSmallCustomToast(String message) {

        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
        TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
        msgTv.setText(message);
        Toast toast = new Toast(context);
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

}

토스트를 사용자 지정하는 간단한 방법,

private void MsgDisplay(String Msg, int Size, int Grav){
    Toast toast = Toast.makeText(this, Msg, Toast.LENGTH_LONG);
    TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
    v.setTextColor(Color.rgb(241, 196, 15));
    v.setTextSize(Size);
    v.setGravity(Gravity.CENTER);
    v.setShadowLayer(1.5f, -1, 1, Color.BLACK);
    if(Grav == 1){
        toast.setGravity(Gravity.BOTTOM, 0, 120);
    }else{
        toast.setGravity(Gravity.BOTTOM, 0, 10);
    }
    toast.show();
}

layout_ * 매개 변수가 제대로 사용되지 않는 문제를 방지하려면 사용자 지정 레이아웃을 확장 할 때 올바른 ViewGroup을 부모로 지정했는지 확인해야합니다.

여기에서 많은 예제가 null을 전달하지만 대신 기존 Toast ViewGroup을 부모로 전달할 수 있습니다.

val toast = Toast.makeText(this, "", Toast.LENGTH_LONG)
val layout = LayoutInflater.from(this).inflate(R.layout.view_custom_toast, toast.view.parent as? ViewGroup?)
toast.view = layout
toast.show()

여기에서 기존 Toast보기를 사용자 정의보기로 바꿉니다. 레이아웃 "레이아웃"에 대한 참조가 있으면 여기에 포함될 수있는 이미지 / 텍스트보기를 업데이트 할 수 있습니다.

이 솔루션은 또한 "창 관리자에 연결되지 않은보기"충돌이 null을 부모로 사용하는 것을 방지합니다.

또한 ConstraintLayout을 사용자 지정 레이아웃 루트로 사용하지 마십시오. 이것은 Toast 내에서 사용될 때 작동하지 않는 것 같습니다.


모든 Kotlin 사용자 용

다음과 같이 확장을 만들 수 있습니다.

fun FragmentActivity.showCustomToast(message : String,color : Int) {
 val toastView = findViewById<TextView>(R.id.toast_view)
 toastView.text = message
 toastView.visibility = View.VISIBLE
 toastView.setBackgroundColor(color)

 // create a daemon thread
 val timer = Timer("schedule", true)

 // schedule a single event
 timer.schedule(2000) {
    runOnUiThread { toastView.visibility = View.GONE }
 }
}

val inflater = layoutInflater
val container: ViewGroup = findViewById(R.id.custom_toast_container)
val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
val text: TextView = layout.findViewById(R.id.text)
text.text = "This is a custom toast"
with (Toast(applicationContext)) {
    setGravity(Gravity.CENTER_VERTICAL, 0, 0)
    duration = Toast.LENGTH_LONG
    view = layout
    show()
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              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"
              />
</LinearLayout>

참조 : https://developer.android.com/guide/topics/ui/notifiers/toasts

참고 URL : https://stackoverflow.com/questions/11288475/custom-toast-on-android-a-simple-example

반응형