Setting button alignment programmatically

2019-01-29 11:26发布

I'm creating some 50 button dynamically.
Text is getting set as followed:

btn.Text=result.Rows[i]["Col1"].ToString()+"\n"+result.Rows[i]["Col2"].ToString()
+"\n"+result.Rows[i]["Col3"].ToString();

where result is DataTable & btn is object for button.

Now the problem is some of the buttons are not getting displayed appropriately.

Referring to screenshot below,

in img1 - An unnecessary blank line is getting displayed after the first row.
in img2 - Text is not center aligned.
in img3 - TATAMOTORS is not getting displayed in single line even though there is a space on either side of t he button.

Please note that I'm not setting padding which can be the reason for this.

Any idea how to solve this?
Also, how alignment of text of a button can be set programmatically?

I know that this is not the Best of the question, but after spending hours on it, I'm unable to crack it.

Any help appreciated...

Screen shot

4条回答
Melony?
2楼-- · 2019-01-29 11:43

Alignment of button content can be set with .setGravity(int)

查看更多
对你真心纯属浪费
3楼-- · 2019-01-29 11:48

In the original question, I wonder if the source text contained some extra space characters? That would explain img1 and img2.

Anyway, my need to left-align the text in a button led me to this page, and here's the solution I ended up with, based on Alix Bloom's answer:

Button myButton = new Button(getActivity());
myButton(Gravity.LEFT);
查看更多
Juvenile、少年°
4楼-- · 2019-01-29 11:51
Button myButton = new Button();
myButton.setGravity(Gravity.RIGHT);   //LEFT

Hope this help you. Worked for my (i was also strugling with this issue for some time)

查看更多
别忘想泡老子
5楼-- · 2019-01-29 11:56

You can set the gravity of the button to customize how the text is aligned. This is exposed on the button by using the Gravity property. From the docs:

Sets the horizontal alignment of the text and the vertical gravity that will be used when there is extra space in the TextView beyond what is required for the text itself.

The values you can assign are found in the GravityFlags enum. For example:

button.Gravity = GravityFlags.Center;
查看更多
登录 后发表回答