public class MainActivity extends Activity {java
private View viewToast;android
@Overrideide
protected void onCreate(Bundle savedInstanceState) {佈局
super.onCreate(savedInstanceState);this
setContentView(R.layout.activity_main);spa
Button bt = (Button) findViewById(R.id.bt);code
}orm
// 點擊按鈕彈出吐司xml
public void showToast(View view) {rem
viewToast = View.inflate(this, R.layout.view_show_address, null);
// 獲取窗口管理者
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
// wm.addView(視圖, 佈局參數); xml
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;// layout_height
params.width = WindowManager.LayoutParams.WRAP_CONTENT;// layout_width
params.gravity = Gravity.TOP | Gravity.LEFT;// 左上對齊
params.x = 50;// 認爲頂級佈局是一相絕對佈局
params.y = 50;
// 相關參數
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE// 不能彙集
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE// 不能拖動
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;// 高亮
params.format = PixelFormat.TRANSLUCENT;// 背景透明 background
params.type = WindowManager.LayoutParams.TYPE_TOAST;// 類型,能夠設置彈出吐司的級別
wm.addView(viewToast, params);
}
// 點擊按鈕關閉吐司
public void closeToast(View view) {
// 獲取窗口管理者
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
//移除吐司的方法
wm.removeView(viewToast);
}
}
Activity的佈局:
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/bt"
android:text="彈出吐司"
android:onClick="showToast"
/>
<Button
android:layout_marginTop="200dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/close"
android:text="關閉吐司"
android:onClick="closeToast"
/>
</RelativeLayout>
吐司界面的佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#3F3F3F"
tools:context="com.itheima.mobilesafe70.MainActivity" >
<!-- 標題 -->
<TextView
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:drawableLeft="@drawable/ic_launcher"
android:id="@+id/address"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=" 自定義吐司窗口"
android:textSize="25sp" />
</LinearLayout>
最後記得加權限,否則會報錯.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />