Set position by percent - Android DisplayMetrics

*爱你&永不变心* 提交于 2020-01-11 12:39:09

问题


I like to use percents for all position in my apps . I always use same system. I am new at android programming.

This is the class :

public class SCREEN  {

    DisplayMetrics dm = new DisplayMetrics();
    Point size_ = new Point();
    int width;
    int height;

  //  DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();

    SCREEN (Context CONTEXT_) {
        dm = CONTEXT_.getResources().getDisplayMetrics();
        int densityDpi = dm.densityDpi;
        height = dm.heightPixels;
        width = dm.widthPixels;
    }

    // get full width
    public int WIDTH() {
        return width;
    }
    public int HEIGHT(){
        return height;
    }
    public int W( int PER_ ){
        return width/100*PER_;
    }
    public int H( int PER_   ){
        return height/100*PER_;
    }
}

Example of usage :

EKRAN = new SCREEN();

MENU1.setX( (float) EKRAN.W( 50 ) );

This means that MENU1 button x position must be on center of the screen but it isnt . Its little smaller value like 42%.

Maybe my bug is relationship between int - float

Here is screenshot (FrameLayout) : I put this code for this button - It means x = 0 , y = 0 , width = half of screen but it is not :

 final Button BTN1 = new Button(this);
    BTN1.setText( String.valueOf( EKRAN.H( 0 ) ) );

    BTN1.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
    VEIW_MAIN.addView(BTN1);

    BTN1.setY( (float)  EKRAN.H( 0 ) );
    BTN1.setX( (float) EKRAN.W( 0 ) );
    BTN1.setWidth( (int)  EKRAN.W( 50 ) );

Important : This work EKRAN.WIDTH()/5 = 216  , but EKRAN.W(20) = 200
My current screen i is 1080 . Only this EKRAN.WIDTH()/2 give me 540 .
Even EKRAN.WIDTH()/100*50 give me 500 ... Where is the 40pix ?! 

回答1:


The best answer is: Don't use percentages. It wont work out. Use RelativeLayout and properties like layout_gravity center_vertical and such things.



来源:https://stackoverflow.com/questions/40397356/set-position-by-percent-android-displaymetrics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!