Android:将按钮高度设置为与宽度相同 [英] Android: set button height same as width
本文介绍了Android:将按钮高度设置为与宽度相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的布局的一部分.我需要按钮才能成为完美的正方形.行中将有4个按钮.滚动视图中将有更多行.每行将适合任何屏幕尺寸的屏幕宽度.我已经尝试了很多解决方案,但是没有达到我想要的效果.然后,我还需要使按钮具有动态的文本,以便每次填充按钮的宽度.有什么解决办法吗?我已经尝试了好几个星期.
This is part of my layout. I need buttons to be perfect squares. There will be 4 buttons in row. There will be more rows in scrollview. Every row will fit the screen width for any screen size. I have tried ton of solutions but nothing works as I want to. Then also I need to have the text dynamic as the buttons so it everytime fills the button width. Is there any solution? I am trying this for weeks.
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp">
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:text="@string/r1960"
android:textColor="#ffffff"
android:textSize="@dimen/loptatext"
android:shadowColor="#000000"
android:shadowRadius="7"
android:layout_weight="1"
android:background="@drawable/tlacitko_stav" />
<Button
android:id="@+id/button5"
android:layout_width="match_parent"
android:text="@string/r1964"
android:textColor="#ffffff"
android:textSize="@dimen/loptatext"
android:shadowColor="#000000"
android:shadowRadius="7"
android:layout_weight="1"
android:background="@drawable/tlacitko_stav" />
<Button
android:id="@+id/button6"
android:layout_width="match_parent"
android:text="@string/r1968"
android:textColor="#ffffff"
android:textSize="@dimen/loptatext"
android:shadowColor="#000000"
android:shadowRadius="7"
android:layout_weight="1"
android:background="@drawable/tlacitko_stav" />
<Button
android:id="@+id/button7"
android:layout_width="match_parent"
android:text="@string/r1972"
android:textColor="#ffffff"
android:textSize="@dimen/loptatext"
android:shadowColor="#000000"
android:shadowRadius="7"
android:layout_weight="1"
android:background="@drawable/tlacitko_stav" />
</TableRow>
推荐答案
您可以扩展Button并将其强制为方形,如下所示:
You could extend Button and force it to be square, like this:
public class SquareButton extends Button {
public SquareButton(Context context) {
super(context);
}
public SquareButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public SquareButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}
}
这篇关于Android:将按钮高度设置为与宽度相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文