Android 以编程方式在ImageButton上居中显示文本视图

Android 以编程方式在ImageButton上居中显示文本视图,android,Android,我需要将TextView设置为以ImageButton为中心,但要使用code。我可以设置文字,但不能将其居中 代码: RelativeLayout rLayout = new RelativeLayout(this); TextView textView = new TextView(this); textView.setText("text"); textView.setTextSize(25); textView.setGravity(Gr

我需要将
TextView
设置为以
ImageButton
为中心,但要使用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);

这段代码设置了imageButton上的文本,但将其设置在左上角。

不清楚您在问什么……但如果我理解正确,您必须在将其添加到父级之前在TextView上设置。此外,还必须在父项中添加规则RelativeLayout.CENTER

比如说:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size, size)
params.addRule(RelativeLayout.CENTER_IN_PARENT)
textView.setLayoutParams(params)
或者其他一些适合您的用例的规则组合。

试试看

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

iButton.setLayoutParams(params);

无法在iButton中设置重力,因此无法工作。设置文本和按钮之间的距离。尝试将文本大小从25减小到16我只需要将文本放在imageButton的中心。为什么不将按钮与文本和背景图像一起使用,而不是imageButton和TextView?