2013年4月27日 星期六

[Android] 自訂顯示快顯(custom toast)

一般預設的寫法是像這樣
Toast.makeText(getApplicationContext(), "預設的顯示快顯", Toast.LENGTH_SHORT).show();

今天來實作一個帶圖片的的toast
首先先加入toast要用的圖案,在這裡加入一個icon.png












MainActivity.java
package com.example.customtoast;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button mToastButton;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mToastButton = (Button) findViewById(R.id.toast_button);
        mToastButton.setOnClickListener(this);
       
    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.toast_button) {
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast,
                    (ViewGroup) findViewById(R.id.custom_toast));
          
         Toast toast = new Toast(getApplicationContext());
          toast.setGravity(Gravity.CENTER, 0, 0);
          toast.setDuration(Toast.LENGTH_LONG);
          toast.setView(layout);
          toast.show();
        }
    }
}

制作一個toast的layout
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"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:background="@android:color/black">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/toast_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a custom toast"
        android:textAppearance="@android:attr/textAppearanceLarge"
        android:textColor="@android:color/white" />
    
    </LinearLayout>

res/layout/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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/toast_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp"
        android:text="Click Here to show Toast" />

</RelativeLayout>

結果:

沒有留言:

張貼留言