프로그래밍/Android

Toast View 만들기

chance 2009. 11. 9. 00:37

 

 

이번엔 커스텀 토스트 뷰를 만들어 볼 예정.

 

의례 하는데로 xml 레이아웃을 구성한다.

다이얼로그와 같이 토스트뷰를 위한 레이아웃을 별도로 구성하고,

해당 레이아웃에 원하는 뷰들을 배치한다.

 

toast_layout.xml로 레이아웃을 생성한다.

 

<LinearLayout xmlns:android:"http://schemas.android.com/apk/res/android"

android:id="@+id/toast_layout_id"

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>

 

레이아웃 구성이 끝나면, 소스코드에서 호출해 사용하면 된다.

다이얼로그와 같이 LayoutInflater 객체를 사용해 xml로 부터 레이아웃을

얻어와 사용한다.(getLayoutInflater() 혹은 getSystemService() 사용)

 

LayoutInflater inflater = getLayoutInflater();

View layout = inflater.inflate( R.layout.toast_layout, (ViewGroup) findViewById( R.id.toast_layout_id) );

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();