Как сохранить соотношение сторон на кнопках изображения в андроиде?
У меня есть 5 квадратных кнопок изображения, которые я хочу выстроить рядом друг с другом в нижней части экрана. У меня есть каждый набор (разные идентификаторы) как:
<ImageButton
android:id="@+id/box1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:layout_weight="1"
android:layout_margin="1dp"
/>
и у меня есть фон, назначенный в главном java следующим образом:
int[] imageIds = new int[] {R.id.box1,R.id.box2,R.id.box3,R.id.box4,R.id.box5};
for(int i = 0; i<5; i++){
imageButtons[i] = (ImageButton) findViewById(imageIds[i]);
imageButtons[i].setBackgroundResource(R.drawable.blank);
}
То, что я хотел бы сделать, это масштабировать ширину, чтобы она аккуратно располагалась бок о бок в нижней части экрана (что теперь делает это нормально), но автоматически увеличивайте высоту, чтобы она соответствовала ширине. Это возможно? Я не хочу использовать setImageSource, потому что тогда он помещает рамку вокруг кнопки изображения.
Ответы
Ответ 1
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutButtons">
<com.package.SquareButton
android:layout_height="fill_parent"
android:layout_width="0dip"
android:layout_weight="1"
<ImageView
android:id="@+id/box1"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
</com.package.SquareButton>
<com.package.SquareButton
android:layout_height="fill_parent"
android:layout_width="0dip"
android:layout_weight="1"
<ImageView
android:id="@+id/box2"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
</com.package.SquareButton>
.........
</LinearLayout>
И затем добавьте этот класс пользовательской кнопки:
public class SquareButton extends LinearLayout {
public SquareButton(Context context) {
super(context);
}
public SquareButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
// This is used to make square buttons.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
Ответ 2
У меня была аналогичная головная боль, пытаясь получить мои кнопки подряд. Решение, которое я нашел, заключалось в использовании ImageButton
и свойства android:src
(setImageSource
в коде) в сочетании с android:background="@null"
Как я понимаю, фон кнопки изображения не влияет на adjustViewBounds
, а только imageView
, который вы установили в android:src
.
Поведение по умолчанию - это дать квадратную кнопку с изображением в середине. Вы можете переопределить это, установив фон @null
, который оставит вам только изображение.
Затем вы можете использовать либо LinearLayout
, либо таблицу для размещения ваших кнопок. Я сделал все в XML и использовал следующий макет, чтобы создать ряд из двух кнопок внизу экрана, которые увеличивают или уменьшают пропорции с различными размерами экранов устройства. Надеюсь, это поможет.
<TableLayout
android:id="@+id/tableLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dip"
android:stretchColumns="*">
<TableRow>
<ImageButton
android:id="@+id/button_one"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="0.5"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:onClick="clickOne"
android:background="@null"
android:src="@drawable/button_one_drawable" />
<ImageButton
android:id="@+id/button_two"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="0.5"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:onClick="clickTwo"
android:background="@null"
android:src="@drawable/button_two_drawable" />
</TableRow>
</TableLayout>
Ответ 3
Вместо
android:scaleType="fitXY"
использование:
android:scaleType="centerInside"
EDIT1: Попробуйте следующее:
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutToInflateButtons"
>
<ImageButton
android:id="@+id/box1"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_weight="1"
android:layout_margin="1dp"
/>
</LinearLayout>
Ответ 4
Я уверен, что вы хотите иметь 5 кнопок ширины/высоты EQUAL. Если это так, возьмите LinearLayout и поместите все эти 5 кнопок с layout_width="0dip"
и layout_weight="1"
Например:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutButtons">
<ImageButton
android:id="@+id/box1"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="1"/>
<ImageButton
android:id="@+id/box2"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:layout_weight="1"/>
.........
</LinearLayout>
Ответ 5
Вы можете использовать относительную компоновку Google Percent, которая поможет вам управлять соотношением сторон просмотра.
Вы можете использовать его так:
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/box1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitXY"
app:layout_aspectRatio="100%"
android:layout_weight="1"
/>
</android.support.percent.PercentFrameLayout>
Соотношение сторон 100% сделает ширину равной высоте.
Пример:
android:layout_width="300dp"
app:layout_aspectRatio="178%"
ширина 178% высоты. Это формат, который layout_aspectRatio ожидает
Вы можете прочитать его подробно здесь
Ответ 6
После проверки образца приложения ввода-вывода Google с этого года я обнаружил, что Google использует значения dimen для указания высоты или ширины varios на основе типа экрана. Для получения дополнительной информации вы можете проверить исходный код http://code.google.com/p/iosched/.
Вы можете указать высоту кнопки для примера в значениях-xhdpi или values-sw720dp как:
<resources>
<dimen name="button_height">50dp</dimen>
</resources>
И тогда вы можете просто использовать это значение размера при указании высоты:
android:layout_height="@dimen/button_height"
Ответ 7
Задайте ширину кнопок изображения на fill_parent
и используйте тип сканирований fitStart
для изображений, которые обнимают левое поле, и fitEnd
для тех, которые находятся справа. Должен сделать трюк, по крайней мере, насколько ваш пример изображения. У вас могут быть некоторые проблемы с интервалом, если пропорциональная ширина изображений превышает ширину экрана, но она должна работать для вас.
Ответ 8
ViewGroup.LayoutParams params = imageButtonName.getLayoutParams();
// Changes the height(or width) and width(or height) to the specified
params.height = layout.getWidth();
Ответ 9
Посмотрите на создание настраиваемого ImageButton. Мне это нравится, потому что его один класс. Вот кнопка, которая регулирует ее высоту в зависимости от соотношения сторон изображения. Я полагаю, вы можете настроить ваши потребности:
public class AspectImageButton extends ImageButton {
public AspectImageButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.getDrawable();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
Drawable d=this.getDrawable(); //grab the drawable
float fAspectRatio=(float)d.getIntrinsicWidth()/(float)d.getIntrinsicHeight();
float fHeight=(float)width/fAspectRatio;//get new height
setMeasuredDimension(width, (int)fHeight);
}
public AspectImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public AspectImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
}
то в xml просто используйте его так:
<com.package.AspectImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/home_1b"
android:background="@null"
android:scaleType="fitXY"
android:adjustViewBounds="true" />