Sunday, February 14, 2016

Android Set Control Width Dynamically Android Studio Java

In this tutorial I will show you how to create a Control with Width that will be same on all device regardless of there screen size.

So doesn't matter if your screen size is 5' or 4' your control will adjust itself automatically according to the screen size.

1:      super.onCreate(savedInstanceState);  
2:      RelativeLayout PageLayout = new RelativeLayout(this);  
3:      RelativeLayout.LayoutParams txtLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);  
4:      txtLayout.addRule(RelativeLayout.CENTER_HORIZONTAL);  
5:      txtLayout.addRule(RelativeLayout.CENTER_VERTICAL);  
6:      EditText txtLogin = new EditText(this);  
7:      Resources r = getResources();  
8:      int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,200,r.getDisplayMetrics());  
9:      txtLogin.setWidth(px);  
10:      PageLayout.addView(txtLogin,txtLayout);  
11:      setContentView(PageLayout);  
Note that instead of defining width 200 static we are converting this into pixel according to device screen see line no. 8

After we get the px value which is of type in we can pass this value to setWitdh method.

I hope that it was informative for you and I would like to Thank you for reading.

No comments:

Post a Comment