Android中Toast的自定义
<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" android:background="#000000" > <Button android:id="@+id/customToast" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="CustomToast"/> </RelativeLayout>
这是main.xml,main.xml中的代码很简单就只有一个Button
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp" android:background="@null" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_marginRight="10dp"/> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#fff"/> </LinearLayout>
这个就是自定义Toast的布局。需要的image和text在Java代码中自定义添加的!
package com.msr.toast; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button customToast; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); customToast = (Button)findViewById(R.id.customToast); customToast.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast toast = new Toast(MainActivity.this); LayoutInflater inflater = MainActivity.this.getLayoutInflater(); View toastLayout = inflater.inflate(R.layout.customtoast, null); TextView text = (TextView)toastLayout.findViewById(R.id.text); text.setText("You are my angle!"); ImageView image = (ImageView)toastLayout.findViewById(R.id.image); image.setBackgroundResource(R.drawable.ic_launcher); toast.setView(toastLayout); toast.setDuration(Toast.LENGTH_LONG); toast.show(); } }); } }
这个就是Java中代码。 这个自定义感觉很有必要!特别是在提示什么的时候,如果还是系统自带的有点难看!