Juan Silvio
Juan Silvio

Reputation: 49

Center TextView on ImageButton Programmatically

I need to set TextView centered on a ImageButton, but using code. I can set a text on, but I can't center it.

code:

RelativeLayout rLayout = new RelativeLayout(this);            

TextView textView = new TextView(this);
textView.setText("text");
textView.setTextSize(25);            
textView.setGravity(Gravity.CENTER);

final ImageButton iButton = new ImageButton(this);
iButton.setImageResource(R.drawable.button);
iButton.setBackgroundColor(Color.TRANSPARENT);

rLayout.addView(iButton);
rLayout.addView(textView);
linear.addView(rLayout);

This code set text on imageButton, but set it in left-top.

Upvotes: 1

Views: 63

Answers (2)

phpdroid
phpdroid

Reputation: 1663

so try

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,  LayoutParams.FILL_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.CENTER;

iButton.setLayoutParams(params);

Upvotes: 1

Submersed
Submersed

Reputation: 8870

It's kind of unclear what you're asking...but if I'm understanding correctly, you have to set the RelativeLayout.LayoutParams on the TextView before adding it to the parent. Also, you have to add the rule RelativeLayout.CENTER_IN_PARENT.

So, something like:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size, size)
params.addRule(RelativeLayout.CENTER_IN_PARENT)
textView.setLayoutParams(params)

Or some other combination of rules that fit your usecase.

Upvotes: 1

Related Questions