0

I have created Button View programatically inside LinearLayout with VERTICAL orientation. Below is my code for button view

LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int w=Resources.getSystem().getDisplayMetrics().widthPixels;
        params.setMargins(w/3,0,w/3,0);
        button.setLayoutParams(params);
        button.setText("Hello");
        layout.setGravity(Gravity.CENTER);
layout.addView(button);

But because of the dimensions ButtonView looks different in some low dimension device. For ex. below in low dimension

 _____
|hello|
|_____|

below in high dimension devices,

 _____________
|   hello     |
|_____________|

When I tried wrap content for width and left, right padding for it. Due to the length of the text inside Button, all ButtonView will not look even. For Ex.

 _____________
| Hello World |
|_____________|


 _______
| hello |
|_______|

My goal is to achieve above(mentioned in high dimension) like width for all devices. Thanks in advance.

Kousalya
  • 700
  • 10
  • 29

2 Answers2

0

Maybe you could use wrapContent for width with a paddingHorizontal value?

mimi012
  • 36
  • 6
  • yeah can do that. but in my case, I have multiple button. Each text of button is different. Some text in button is long and some are short. So padding will not be same for all buttons. – Kousalya Dec 30 '20 at 14:51
0

Another thing you can do is using different dimens files:

  • Create dimens.xml in those folders:
    • res/values-ldpi
    • res/values-mdpi
    • res/values-hdpi
    • res/values-xhdpi
    • res/values-xxhdpi
    • res/values-xxxhdpi
  • In those files define a button size for each density:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="button_width">200dp</dimen>
</resources>
  • then, get this value in your code:
int dp = (int) (getResources().getDimension(R.dimen.test) / getResources().getDisplayMetrics().density);

According with this post, you have to divide the result by the phone density.

mimi012
  • 36
  • 6