【发布时间】:2012-01-01 13:16:04
【问题描述】:
我正在尝试使用 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 设置为包裹内容并在父视图中垂直居中。将指标设置为 alignTop 和 toRightOf RadioGroup。然后,对于按钮点击监听器:
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();
}
【问题讨论】:
-
太棒了!而且实现看起来也不错!
标签: android android-relativelayout tabbar viewgroup