经常在与客户沟通过程中,经常看到Toast显示的内容太丑,又无法达到客户要求,如果放到平板上,客户已经习惯Windows的那一套,因此,只有自定义才能更好的显示自己或客户的期望。我就讲一段简单的自定义方法就行。
第一步:准备需要的资源,如Question图标等
第二步:准备一个修饰边框的drawable文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners android:radius="10dp"/>
<solid android:color="#ffffff"/>
<stroke android:width="3dp" android:color="#6699ff"/>
</shape>
第三步:建一个layout文件,内容如下:
<?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:background="@drawable/toastborderstyle"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/help" />
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20dp"
android:text="系统信息提示"
android:textColor="#ffffff"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义Toast测试"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
第四步:就是代码的事了。和其他控件自定义差不多。
package com.example.testui;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button btnCustomToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnCustomToast=(Button)this.findViewById(R.id.btnCustomToast);
btnCustomToast.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast toast=new Toast(this);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
LayoutInflater mInflater=this.getLayoutInflater();
View view=mInflater.inflate(R.layout.toastinfo, null);
toast.setView(view);
toast.show();
}
}
哈哈!目标达到就成!!