Reputation: 2785
I am building a simple text editor. I wanted to align text to left, center and right.
I did following, but does not change the alignment of the text
How do I do this?
EditText txt = (EditText) findViewById(R.id.txt_gcFrontInsideTextData);
if (command == 0 )
{
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.TOP | Gravity.LEFT);
txt.setLayoutParams(p);
}
else if (command == 1)
{
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL);
txt.setLayoutParams(p);
}
else if (command == 2)
{
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, Gravity.TOP | Gravity.RIGHT);
txt.setLayoutParams(p);
}
Upvotes: 0
Views: 2135
Reputation: 16570
All you need to do is use the method setGravity()
directly on the EditText
like this:
EditText txt = (EditText) findViewById(R.id.txt_gcFrontInsideTextData);
switch(command)
{
case 0:
txt.setGravity(Gravity.TOP | Gravity.LEFT);
break;
case 1:
txt.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
break;
case 2:
txt.setGravity(Gravity.TOP | Gravity.RIGHT);
break;
}
Upvotes: 0
Reputation: 9743
First of all, LinearLayout.LayoutParams
constructor does not take gravity as a parameter - third parameter is layout weight.
Field gravity
of LinearLayout.LayoutParams
is in fact layout_gravity, which defines layout aligment inside it's parent.
What you need is
if (command == 0 )
{
txt.setGravity(Gravity.TOP | Gravity.LEFT);
}
for example.
Upvotes: 3