1. 程式人生 > >Android-自定義Toast、LayoutInflater使用其他佈局

Android-自定義Toast、LayoutInflater使用其他佈局

內容:

1.自定義樣式toast

2.再活動中新增其他佈局

實現效果:

步驟:

一、自定義View 引用zidingyixml檔案 生成一個佈局物件

二、採用Toast 的addView() 方法將該物件新增到Toast物件中

三、顯示:Toast.show()

具體實現方法:

public class MainActivity extends Activity {
    Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //應用佈局檔案
        View insideView = LayoutInflater.from(MainActivity.this).inflate(R.layout.cell, null);
        LinearLayout linearLayout = (LinearLayout) insideView.findViewById(R.id.cell);
        ImageView imageView = (ImageView) insideView.findViewById(R.id.image1_Toast);
        TextView textView = (TextView) insideView.findViewById(R.id.textToast);
        imageView.setImageResource(R.drawable.warming);
        textView.setText("你的app 炸了!!");
        //建立提示訊息物件
        toast = new Toast(this);
        toast.setView(insideView);
    }
    //按鈕點選時彈出
    public void prev(View source){
        toast.show();
    }
}

注:R.layout.cell 中的cell 就是自定義的佈局檔案

建立步驟 在/values資料夾下 呢哇一個xml檔案即可,內容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/cell"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/image1_Toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/textToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"/>
</LinearLayout>

最後給出整體的佈局檔案:

<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">
        <Button
            android:onClick="prev"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"/>
</RelativeLayout>

注:採用了 android:onClick="prev" 方法 在佈局檔案中直接添加了點選事件,故MainActivity中不用手動新增onClickListener