[ Toast ]
1. Code
- Toast.makeText(Context context, String message, int duration)
- Context : 일반적으로 Context클래스를 상속한 액티비티를 사용
-
2. 위치및 모양 변경
- setGravity(int gravity, int xOffset, int yOffset)
- setMargin(float horizontalMargin, float verticalMargin)
3. 추가 메소드
- setView(Layout layout); --토스트가 보이는 뷰 설정
- show(); --토스트를 보여줌
4. 별도 Layout을 이용해서 Toast 보여주기
[ 4.1 MainActivity.java ]
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
public void onButton1Clicked(View v) { // 토스트의 모양을정의하고 있는 레이아웃을 인플레이션합니다. LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.toastborder, (ViewGroup) findViewById(R.id.toast_layout_root));
// 레이아웃의 텍스트뷰에 보여줄 문자열을 설정합니다. TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello My Android!");
// 토스트 객체를 만듭니다. Toast toast = new Toast(this); toast.setGravity(Gravity.CENTER, 0, -100); toast.setDuration(Toast.LENGTH_SHORT);
// 토스트에 뷰를 설정합니다. 이 뷰가 토스트로 보여집니다. toast.setView(layout); toast.show(); } } |
[ 4.2 activity_main.xml ]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" >
<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="토스트 보여주기" android:textSize="20dp" android:onClick="onButton1Clicked" />
</RelativeLayout>
|
[ 4.3 toastborder.xml ] - toast를 보여줄 Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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:background="@drawable/toast" /> </LinearLayout> |
[ 4.4 toast.xml ]
- 별도 xml을 이용해서 Toast 색상정의
- /res/drawable/toast.xml
- setView()메소드를 이용해 토스트 객체에 설정한다.
<?xml version="1.0" encoding="UTF-8" ?> <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> |