我想隐藏菜单项和标题(类似于 GMail 应用程序
刷新时出现)。
这可以通过使用WindowManager.addView(View, LayoutParams) 来完成。这是一个在ActionBar 上显示消息的示例,它应该让您对如何继续有一个非常可靠的想法。
布局
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="18sp" />
实施
/** The attribute depicting the size of the {@link ActionBar} */
private static final int[] ACTION_BAR_SIZE = new int[] {
android.R.attr.actionBarSize
};
/** The notification layout */
private TextView mMessage;
private void showLoadingMessage() {
// Remove any previous notifications
removeLoadingMessage();
// Initialize the layout
if (mMessage == null) {
final LayoutInflater inflater = getLayoutInflater();
mMessage = (TextView) inflater.inflate(R.layout.your_layout, null);
mMessage.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
mMessage.setText("Loading...");
}
// Add the View to the Window
getWindowManager().addView(mMessage, getActionBarLayoutParams());
}
private void removeLoadingMessage() {
if (mMessage != null && mMessage.getWindowToken() != null) {
getWindowManager().removeViewImmediate(mMessage);
mMessage = null;
}
}
/**
* To use, @see {@link WindowManager#addView(View, LayoutParams)}
*
* @return The {@link WindowManager.LayoutParams} to assign to a
* {@link View} that can be placed on top of the {@link ActionBar}
*/
private WindowManager.LayoutParams getActionBarLayoutParams() {
// Retrieve the height of the status bar
final Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
final int statusBarHeight = rect.top;
// Retrieve the height of the ActionBar
final TypedArray actionBarSize = obtainStyledAttributes(ACTION_BAR_SIZE);
final int actionBarHeight = actionBarSize.getDimensionPixelSize(0, 0);
actionBarSize.recycle();
// Create the LayoutParams for the View
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
LayoutParams.MATCH_PARENT, actionBarHeight,
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP;
params.x = 0;
params.y = statusBarHeight;
return params;
}
结果
结论
这种实现方式与 Gmail 和其他应用程序非常相似,只是缺少了下拉刷新模式。
当您致电showLoadingMessage 时,请发帖Runnable 或使用View.OnClickListener。你不想太早打电话给WindowManager.addView,否则你会抛出WindowManager.BadTokenException。此外,在Activity.onDestroy 中调用removeLoadingMessage 也很重要,否则您将面临泄漏您添加到Window 的View 的风险。