mobile/android

7_Android_(토스트)

스파이크12 2020. 5. 17. 18:39

Toast.makeToast(context, text, duration).show();

글자보여주는위치 설정

public void setGravity(int gravity, int xOffset, int yOffset);

public void setMargin(float horiziontalMargin, float verticalMargin);

ex) toastView.setGravity(Gravity.TOP|Gravity.TOP, xOffset, yOffset);

(기준점, x좌표, y좌표);

모양바꾸기

// inflater : xml로 정의된 view(또는 menu 등)을 실제 객체화 시키는 용도

1. inflater를 사용한 객체 생성

public void onButton2Clicked(View v){
        // 인플레이터 객체 생성
        LayoutInflater inflater = getLayoutInflater();

		// inflate(읽어드릴 레이아웃 파일명, 최상위레이아웃아이디)
        View layout = inflater.inflate(R.layout.toastborder,
                (ViewGroup)findViewById(R.id.toast_layout_root));
		// 텍스트객체생성
        TextView text = layout.findViewById(R.id.text);

		// 토스트 객체생성
        Toast toast = new Toast(this);
        // 텍스트 객체 세팅
        text.setText("모양 바꾼 토스트");
        // 위치
        toast.setGravity(Gravity.CENTER, 0, -100);
        // 시간
        toast.setDuration(Toast.LENGTH_SHORT);
        // 토스트를 보여줄 레이아웃
        toast.setView(layout);
        toast.show();
}

 

2. /app/res/layout 폴더에 새롭게 만들 토스트의 형태를 정의

<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">
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="32sp"
        android:background="@drawable/toast"
        />

</LinearLayout>

3. @drawble/toast이므로 /app/res/drawable 폴더에 toast.xml 객체생성(토스트의 색상 등)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >
    <stroke
        android:width="4dp"
        android:color="#ffffff00"
        />
    <solid
        android:color="#ff883300"
        />
    <padding
        android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp"
        />
    <corners
        android:radius="15dp"
        />

</shape>