二、Toast
都说Toast对比于Dialog更友好,体现在哪里呢,Toast不打断用户,永远不会获得焦点,灰常巧妙啊!灰常好用啊!
使用Toast很简单:
实例化一个,new;和一个view相关,setView;显示长度;show()就Ok啦。
或者静态方法Toast.makeText(this,"string",//short or long)
果断实例操作下。。。
ActivityToast.java
public class ActivityToast extends Activity {
OnClickListener listener = null;
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new OnClickListener() {
public void onClick(View v) {
setTitle("短时间显示Toast");
showToast(Toast.LENGTH_SHORT);
}
};
setContentView(R.layout.activity_toast);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(listener);
}
protected void showToast(int type) {
View view = inflateView(R.layout.toast);
TextView tv = (TextView) view.findViewById(R.id.content);
tv.setText("啦啦啦德玛西亚");
Toast toast = new Toast(this);
toast.setView(view);
toast.setDuration(type);
toast.show();
}
private View inflateView(int resource) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return vi.inflate(resource, null);
}
}
toast.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/toast_frame">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/default_icon"
/>
<TextView
android:id="@+id/content"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
/>
</LinearLayout>
</FrameLayout>
在网上看到还可以设置位置
加了这句话
toast.setGravity(Gravity.CENTER, 0, 0);
效果: