我正在尝试使用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();
}