6

我正在尝试使用RelativeLayout和RadioGroup在android中创建一个标签栏,该标签栏有一个指示器,该指示器将滑动以指示RadioGroup中的活动RadioButton。

这些是自定义的单选按钮,实际上是在文本上带有图标的矩形,所有内容居中,使用自定义状态选择器作为背景。

这是我当前的层次结构:

<RelativeLayout>       // Main view of the tab bar
  <RadioGroup>         // The buttons
    <RadioButton />
    <RadioButton />
    <RadioButton />
  </RadioGroup>
  <ImageView />        // The indicator
</RelativeLayout>

我的想法是,当单击单选按钮时,我会将指示器与所选单选按钮的顶部和底部对齐(并为其设置动画)。但是,它似乎layout_align<Edge>只适用于兄弟元素,不适用于另一个视图组的成员,即我可以对齐 RadioGroup 本身,但不能对齐其中的 RadioButton。

我曾想过将指示器作为 RadioGroup 的成员,但由于 RadioGroup 是 LinearLayout 的扩展,因此似乎没有办法将其放置在给定 RadioButton 的边缘。

谁能想到我如何解决这个问题?或者也许有比我的动画对齐按钮技术更好的解决方案?

更新 在@superjos 的帮助下,我设法很好地解决了这个问题。

我必须给每个按钮一个已知的高度而不是使用wrap_content(不理想,但对于这个项目,它应该可以正常工作)。使指示器高度与按钮高度匹配。确保 RadioGroup 设置为包裹内容并在父视图中垂直居中。将指示器设置为alignToptoRightOfRadioGroup。然后,对于按钮单击侦听器:

int prevY, newY;
int prevButtonIndex, newButtonIndex;

public void moveIndicator(button, indicator, index) {
  prevY = newY;
  newY = prevY + (index - prevButtonIndex) * button.getHeight();
  TranslateAnimation animation = new TranslateAnimation(0, 0, prevY, newY);
  animation.setDuration(500);
  animation.setFillAfter(true); // stay at final animation position
  indicator.setAnimation();
  animation.start();
}
4

2 回答 2

1

这是我的想法。以下是一些更详细的步骤。

这个想法是让 ImageView 有一个 RadioGroup 兄弟,就像在您的示例中一样。ImageView 最初位于 RadioGroup 的右侧,其水平中间线与第一个(或任何选择的)RadioButton 对齐。

然后,在单击 RadioButton 时,会在运行时构建/配置 TranslateAnimation,以便让 ImageView 垂直移动,直到其中间线与单击的按钮对齐。动画使用fillAfter设置,以便在完成后保持稳定。

脚步:

  • 创建资源以使 ImageView 和 RadioButtons 具有相同的高度,或者使用垂直填充以使它们具有相同的高度。

  • 为了最初将 ImageView 与第一个 RadioButton 对齐,一些 XML足够了:在 ImageView 中附加layout_toRightOflayout_alignTopRadioGroup。为了考虑 RadioGroup 的顶部填充,您可以将其添加到初始 ImageView 顶部填充 XML 属性。或者更好地作为最高利润。

  • 单击 RadioButton 时,创建将应用于 ImageVew 的 TranslateAnimation,仅将 Y 坐标从 0 开始更改为其目标 toY 值(而 from/toX 属性将为 0)。这是由一个公式给出的,例如:

    toY = (ClickedRadioButton.Index - LastClickedRadioButton.Index) * RadioButton.Heigth
    

    这里Index是 RadioButton 在组中的序号位置(例如从 0 到 2)(警告:这是伪代码,不一定是名为Index的现有 Java 字段)。

  • 将动画应用到 ImageView 并启动它。

于 2011-12-07T02:25:33.823 回答
0

您可以自定义 RadioButton 样式,以包含一个 9patched 版本的指示器图像作为选定(可能会检查无线电..)状态的背景。或可绘制

但是,这取决于您希望动画的外观。

例如。

<style name="TabRadioButton" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:background">@drawable/tab_bg</item>
    <item name="android:drawableLeft">@drawable/tab_indicator</item>
</style>
于 2011-12-02T00:51:35.220 回答