你的位置:首页 > 操作系统

[操作系统]自定义Toast的显示效果


Activity:

 1 package com.example.editortoast; 2  3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.Gravity; 6 import android.view.LayoutInflater; 7 import android.view.View; 8 import android.view.View.OnClickListener; 9 import android.widget.TextView;10 import android.widget.Toast;11 12 public class MainActivity extends Activity {13 14   @Override15   protected void onCreate(Bundle savedInstanceState) {16     super.onCreate(savedInstanceState);17     setContentView(R.layout.activity_main);18     findViewById(R.id.bt).setOnClickListener(new OnClickListener() {19 20       @Override21       public void onClick(View v) {22         toastShow();23       }24     });25   }26 27   private void toastShow() {28     LayoutInflater inflater = LayoutInflater.from(getApplicationContext());29     View view = inflater.inflate(R.layout.item_toast, null);30     TextView textView1 = (TextView) view.findViewById(R.id.TextView_1);31     textView1.setText("Toast1");32 33     Toast toast = new Toast(getApplicationContext());34     toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);35     toast.setDuration(0);36     toast.setView(view);37     toast.show();38   }39 }

activity_main.

 1 <RelativeLayout ="http://schemas.android.com/apk/res/android" 2   ="http://schemas.android.com/tools" 3   android:layout_width="match_parent" 4   android:layout_height="match_parent" 5   tools:context="com.example.editortoast.MainActivity" > 6  7   <Button 8     android:id="@+id/bt" 9     android:layout_width="wrap_content"10     android:layout_height="wrap_content"11     android:text="点击" />12 13 </RelativeLayout>

item_toast.

 1 <??> 2 <RelativeLayout ="http://schemas.android.com/apk/res/android" 3   android:layout_width="match_parent" 4   android:layout_height="match_parent" 5   android:orientation="vertical" > 6  7   <ImageView 8     android:id="@+id/image" 9     android:layout_width="80dp"10     android:layout_height="80dp"11     android:layout_centerVertical="true"12     android:src="@drawable/ic_launcher" />13 14   <TextView15     android:id="@+id/TextView_1"16 17     android:textSize="30sp"18     android:textColor="@android:color/holo_red_light"19     android:layout_width="wrap_content"20     android:layout_height="wrap_content"21     android:layout_centerVertical="true"22     android:layout_toRightOf="@id/image" />23 24 </RelativeLayout>