Android RadioButton无法居中

问题描述

我有以下RadioButtons:

enter image description here

它们是通过这种方法以编程方式生成的:

 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);
        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" />

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

enter image description here

我该如何解决

解决方法

之所以会这样,是因为点和文本都是视图的一部分。如果要使文本“居中”,则必须添加paddingEnd。当然,这种填充取决于点的大小。

,

您必须添加:

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

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