How do I have an ActionBar icon/logo that overlaps the content as well?

后端 未结 2 509
名媛妹妹
名媛妹妹 2021-01-01 06:25

I\'m currently making one of my very first applications. I\'m using ActionBarSherlock. I would like to make my logo overlap the actionbar (scrollview).

Currently I h

2条回答
  •  无人及你
    2021-01-01 07:01

    Although the original answer works on some devices, on others the image sits under the status bar. I resolved this by getting the location of the top ActionBar and comparing it to the location of the top of the logo image and then just adding some top padding, as follows:

        // 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);
                            }
                        }
                    }
            );
        }
    

    This worked on a wide range of devices (phones, big/small tablets - inc Kindle Fire HDX) running Android versions 4.0 up to 4.4.4 as well as Android L preview.

提交回复
热议问题