在按钮中更改文本时,按钮正在GridLayout中更改位置

时间:2020-03-26 21:45:07

标签: android android-button android-gridlayout

我有一个充满按钮的GridLayout,文本经常更改。而且总是在更改文本后,按钮有时会向上或向下移动一点,即使它们不应该如此。我还发现按钮上的文本大小有些巧合(我在按钮内自动调整了文本大小)。我还发现,移动的程度随按钮的高度而增加。 有一个动作的gif:

Screenshots of movements of buttons

还有片段xml,其中包含按钮:

    userToRegister.setPassword(passwordEncoder.encode(userToRegister.getPassword()));

如果您需要更多信息,只需写信,我会添加它。非常感谢。

1 个答案:

答案 0 :(得分:1)

请避免对布局中的layout_heightlayout_width中的尺寸进行硬编码,这很明显的原因是不同设备的尺寸会有所不同。

要解决由于按钮文本长度不同而导致的“按钮对齐”问题,请使用嵌套的LinearLayoutlayout_weight属性的组合,如下所示:

  <androidx.gridlayout.widget.GridLayout
    app:columnCount="3"
    app:rowCount="5"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="9sp"
    app:autoSizeMaxTextSize="16sp"
    app:autoSizeStepGranularity="2sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

      <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="45dp">

        <Button
          android:text="@string/button1"
          android:layout_height="match_parent"
          android:layout_weight="1"
          android:layout_width="0dp"/>

        <Button
          android:text="@string/button2"
          android:layout_height="match_parent"
          android:layout_weight="1"
          android:layout_width="0dp"/>

        <Button
          android:text="@string/button3"
          android:layout_height="match_parent"
          android:layout_weight="1"
          android:layout_width="0dp"/>

      </LinearLayout>

      <LinearLayout
        <!-- same as above, but for button 4,5,6 -->
      </LinearLayout>

      <LinearLayout
        <!-- same as above, but for button 7,8,9 -->
      </LinearLayout>

    </LinearLayout>

  </androidx.gridlayout.widget.GridLayout>

以上布局有效,但“文本自动调整大小”无效。 要使其正常工作,需要向所有按钮添加“大小调整”属性。 这可以使用自定义样式来完成。

  <Button
    style="@style/MyButtonStyle"
    android:text="@string/button1"
    android:layout_height="@dimen/max_height_btn"
    android:layout_weight="1"
    android:layout_width="0dp"/>
  <style name="MyButtonStyle" parent="Widget.AppCompat.Button">
    <item name="autoSizeTextType">uniform</item>
    <item name="autoSizeMinTextSize">9sp</item>
    <item name="autoSizeMaxTextSize">16sp</item>
    <item name="autoSizeStepGranularity">2sp</item>
  </style>
相关问题