Search code examples
androidandroid-layoutscreenandroid-relativelayout

Android Relative Layout multiple screen problems


https://i.sstatic.net/jMAiR.png this is my screenshot of the layout

I used Relativelayout when designing the layout and imageButtons, TextViews, Scroll view in my layout which are sized with using dp and sp values. In the screenshot I showed where should the scroll view and textview should actually be placed, when I place them it works ok but the problem comes when trying on other screens.

I made about 9 diffrent layouts wheter it be qualifiers such as layout-swdp or layout-normal to work on multiple screen, but when I create new virtual device's with different screen sizes, resolution sometimes the layout is placed as I wanted and sometimes not. It seems like at the moment I need to create all the screen size,resolution and density combinations to achive what I want but this doesn't seem normal to me, I think it would take around 30 different layout for different combinations at total to place the scroll view and textview to where I want.

The backgroundimage I am using is set to the relative layouts background property. The thing I am asking is what can I do to solve my problem, is it normal to create around 30 different layouts for different screen combinations ? or am I approaching the problem in a wrong way ? or maybe the mistake was in the begining by placing the spots on the background image(using photoshop) where the textviews and scrollview will be placed ? any advice would be appreciated


Solution

  • You can try this:

        /**
        * 
        * @param view
        * @param wantedTop wanted space in original image (in px)
        * @param originBgSize if images in drawble-mdpi, drawable-hdpi,... have same ratio, you can use any size of them 
        */
        @SuppressLint("NewApi")
        private void calSize(View view, int wantedTop, Point originBgSize) { 
        double imageH = originBgSize.y;
        // get your screen size in pixel
        Display d = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
          size.x = d.getWidth();
          size.y = d.getHeight();
        }
        else {
          d.getSize(size);
        }
        double ratioH = size.y / imageH; 
        int convertedTop = (int) (wantedTop * ratioH);
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (params instanceof MarginLayoutParams) {
          ((MarginLayoutParams) params).topMargin = convertedTop;
          view.setLayoutParams(params);
        }
        }
    

    Then in OnCreated:

        View tv = null;// your text view here;
        // I assume that your image dimension is 720x1014, and the top position you want is 55px
        Point oriSize = new Point(720, 1024); 
        calSize(tv, 55, oriSize);
    

    Hope this works;