搜尋此網誌

2012年5月16日 星期三

Android toast demonstrations

1. Toast是一種短暫提示訊息, 訊息提示完後便會自動消失,
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

public class ToastDemoActivity extends Activity {
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

2.我們也可以客製化自己想要的toast message. 首先將toast_layout.xml放到res/layout目錄下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/toast_layout_root"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              android:background="#DAAA"
              >
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#0F1"
              />
    
    <TextView android:id="@+id/text2"
              android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FF2"
              />
</LinearLayout>
然後修改上一個範例的程式碼如下所示:
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ToastDemoActivity extends Activity {
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.toast_layout,
                                       (ViewGroup) findViewById(R.id.toast_layout_root));

        TextView text = (TextView) layout.findViewById(R.id.text);
        text.setText("Hello! This is a custom toast!\n");
        
        TextView text2 = (TextView) layout.findViewById(R.id.text2);
        text2.setText("Hello! This is a custom toast2!");

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

其中toast.setView這一行程式會把客製化之後的view, 設回toast object. 進而達到改變顯示的文字.
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);會改變toast顯示的位置
toast.setDuration(Toast.LENGTH_LONG);會改變訊息顯示的長度
參考自Android Developers Guide

沒有留言:

張貼留言