Set Percentage Position - Android DisplayMetrics

I like to use percentages for all positions in my applications. I always use the same system. I am new to 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_; } } 

Usage example:

 EKRAN = new SCREEN(); MENU1.setX( (float) EKRAN.W( 50 ) ); 

This means that the position of the MENU1 x button should be in the center of the screen, but this is not the case. Its small lower value, for example, 42%.

Maybe my mistake is the relation between int-float

Here is a screenshot (FrameLayout): I put this code for this button. This means that x = 0, y = 0, width = half the screen, but this is not the case:

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

enter image description here

 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
android set position percentage
Nov 03 '16 at 9:00
source share
1 answer

The best answer: Do not use interest. This will not work. Use RelativeLayout and properties like layout_gravity center_vertical etc.

0
Nov 03 '16 at 9:42 on
source share



All Articles