android中有三種通知方式:土司通知、狀態欄通知、對話框通知。這裏我們介紹土司通知以及自定義土司通知的使用。
整體思路:在xml文件中定義兩個button控件,並分別設置它的點擊事件,在第一個點擊事件中定義Toast對象,設置它的位置並顯示。在第二個點擊事件中綁定一個自己編寫的xml文件,設置該xml文件中控件的屬性,設置它的位置並顯示。
activity_main.xml文件:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="149dp"
android:text="顯示普通通知" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:text="自定義通知" />
dialog.xml文件:
<?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="#ADD"
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:textColor="#FFF"
/>
</LinearLayout>
MainActivity.java文件:
public class MainActivity extends Activity {
private Button button;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// 標準的toast顯示在底端居中的位置
Toast toast = Toast.makeText(MainActivity.this, "消息提示",
Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
button2=(Button)findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast toast=new Toast(MainActivity.this);
// 加載自定義佈局
View view=LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog, null);
ImageView imageView=(ImageView)view.findViewById(R.id.image);
imageView.setImageResource(R.drawable.ic_launcher);
TextView textView=(TextView)view.findViewById(R.id.text);
textView.setText("自定義的土司通知");
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
// 加載自定義的佈局
toast.setView(view);
toast.show();
// 統一UI風格,需要自定義的通知,聲明在一個類中,可以反覆調用
// (把反覆出現的一段代碼寫在一個類中,使用的時候方便調用)
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}