Set position by percent - Android DisplayMetrics

2019-03-02 12:41发布

问题:

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.