刚才在查看android api的时候,无意间看到Toast的使用技巧。想想之前做过的项目,提示话语总是显得那么生硬。掌握自定义Toast相当简单,别忽视了这个开发技巧,积少成多,让自己变得优秀。
平时我们使用toast通常都是用makeText()方法实例化一个Toast对象。该方法需要三个参数:当前应用的Context,文本消息,和toast的持续时间。该方法返回一个实例化过的Toast对象,可以用show()方法将该toast通知显示出来
Context context = getApplicationContext();
CharSequence text = "Hello toast!"
intduration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration).show();
大多素情况下我们都在activity中使用(以MainActivity为例)
Toast.makeText(MainActivity.this, "提示话语", 1000).show();
首先,我们先为自己想要的toast设计一个界面(和我们设计view一样,需要一个xml布局文件),布局的id为toast_layout_root,名字为mytoast
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#DAAA"
android:orientation="horizontal"
android:padding="10dp" >
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:textColor="#ffffff" />
</LinearLayout>
然后我们就可以在我们的代码里面运行我们的toast(具体我用MainActivity为例)
package com.example.mytoast;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button click;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
<span style="color:#ff0000;"> LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.mytoast,
(ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! 这是我的自定义Toast");
Toast toast = new Toast(getApplicationContext());
//设置在屏幕中的位置
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
//设置持续时间
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();</span>
}
});
}
}
点击我们的按钮可以启动我们自定义的toast,这里用了控制toast位置的函数setGravity(int, int, int)方法来改变其位置。三个参数分别是:一个Gravity常量,一个x方向的偏移值和一个y方向的偏移值。
看看运行结果
值得注意的是,平时我们toast大多数是在当前焦点Activity进行提示的,如果你从Service创建一条toast消息,它会显示在当前焦点的activity之上。