Android RadioButton 没有居中

Android RadioButton not centering

我有以下单选按钮:

它们是在此方法中以编程方式生成的:

 private void initializeAbilityComponents() {
    rgAbility = view.findViewById(R.id.rgAbility);

    for (int i = 0; i < abilities.size(); i++) {
        RadioButton radioButton = new RadioButton(context);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(4,4,4,4);
        radioButton.setLayoutParams(layoutParams);
        radioButton.setText(abilities.get(i).getName());
        radioButton.setId(i);
        radioButton.setGravity(Gravity.CENTER);
        PokemonUtils.setRoundedBackgroundColorToView(radioButton,selectedPokemon.getColor());
        rgAbility.addView(radioButton);
    }

并添加到此 xml RadioGroup:

  <RadioGroup
                android:id="@+id/rgAbility"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="6dp"
                android:layout_marginEnd="6dp"
                android:layout_marginBottom="4dp"
                android:layoutAnimation="@anim/default_layout_right_to_left_animation"
                android:orientation="vertical" />

但是,如您所见,它们并没有真正居中,当我居中时我期望的输出是这样的:

我该如何解决这个问题?

发生这种情况是因为点和文本都是视图的一部分。如果你想让文字“更居中”,你必须添加paddingEnd。当然这个填充取决于点的大小。

您必须添加:

radioButton.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
radioButton.setPadding(0,0,100,0); //left, top, right, bottom

右侧值为 100 时,您将文本向左移动