自定义Toast的显示效果

时间:2022-01-05 04:44:29

自定义Toast的显示效果

Activity:

 package com.example.editortoast;

 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.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.bt).setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
toastShow();
}
});
} private void toastShow() {
LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
View view = inflater.inflate(R.layout.item_toast, null);
TextView textView1 = (TextView) view.findViewById(R.id.TextView_1);
textView1.setText("Toast1"); Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(0);
toast.setView(view);
toast.show();
}
}

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="com.example.editortoast.MainActivity" > <Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击" /> </RelativeLayout>

item_toast.xml:

 <?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:orientation="vertical" > <ImageView
android:id="@+id/image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" /> <TextView
android:id="@+id/TextView_1" android:textSize="30sp"
android:textColor="@android:color/holo_red_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/image" /> </RelativeLayout>