我如何拥有与内容重叠的ActionBar图标/徽标?
我目前正在制作我的第一个应用程序之一。 我正在使用ActionBarSherlock。 我想让我的徽标与动作栏重叠(scrollview)。
目前我有main_activity.xml。 在MainActivity.java中,我使用setContentView来查看main_activity.xml。 之后我使用getSupportActionBar()进行ActionBarSherlock。 我已经尝试过使用RelativeLayout(http://www.mkyong.com/android/android-relativelayout-example/)。 这确实不起作用,因为有多个布局。
所以我已经尝试了一些左右的东西,但它总是在动作栏的前面或后面,或者在到达内容之前停止。 这是因为两种不同的布局,这就是我所知道的。 但是我怎么能解决这个问题呢? 可能吗? 提前致谢!
我想要的是: http : //f.cl.ly/items/3N0w243N1t2Q3i1H1f1k/Untitled-1.png
你可以:
A.将图像分成两部分
将顶部作为ActionBar徽标,然后在内容上显示底部。
B.使用单个图像
您需要一个仅包含您的徽标的布局文件(您可能需要在LinearLayout
类似ImageView
的内容,以便您可以轻松设置正确的边距)。 然后在为您的活动调用setContentView
之后,添加您的徽标视图:
ViewGroup decorViewGroup = (ViewGroup) getWindow().getDecorView(); decorViewGroup.addView(logoView);
使用布局文件
示例布局文件(logo_view.xml):
膨胀布局文件:
LayoutInflater inflater = LayoutInflater.from(this); View logoView = inflater.inflate(R.layout.logo_view, null, false);
虽然原始答案适用于某些设备,但在其他设备上,图像位于状态栏下方。 我通过获取顶部ActionBar的位置并将其与徽标图像顶部的位置进行比较然后只添加一些顶部填充来解决这个问题,如下所示:
// Inflate logo layout LayoutInflater inflater = LayoutInflater.from(this); final View logoView = inflater.inflate(R.layout.menu_logo, null); // Add logo to view ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView(); viewGroup.addView(logoView); // Adjust the logo position int resId = getResources().getIdentifier("action_bar_container", "id", "android"); final View actionBarView = viewGroup.findViewById(resId); if (actionBarView != null) { actionBarView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { // Remove the listener if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { actionBarView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { actionBarView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } // Measure views int[] location = new int[2]; actionBarView.getLocationOnScreen(location); int[] logoLocation = new int[2]; logoView.getLocationOnScreen(logoLocation); // Add top padding if necessary if (location[1] > logoLocation[1]) { logoView.setPadding(0, location[1] - logoLocation[1], 0, 0); } } } ); }
这适用于运行Android版本4.0至4.4.4以及Android L预览的各种设备(手机,大/小平板电脑 – 包括Kindle Fire HDX)。