在GridView中拉伸的按钮

时间:2015-04-19 22:35:10

标签: android button gridview

我有一个网格视图和一个自定义适配器来创建可变数量的按钮。所有人都应该保持他们共同背景的比例(正方形)。

但我的问题是我不能让我的网格视图拉伸他们保持他们的“比率”高度/宽度。它们根本不是正方形..

最好的是他们保持所有的平方并调整大小以填满屏幕。

这是我的适配器代码

 public class ButtonAdapter extends BaseAdapter {
    private Context mContext;


    public ButtonAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return size*size;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Button btn;
        if (convertView == null) {
            btn = new Button(mContext);
            btn.setPadding(2, 2, 2, 2);
        }
        else {
            btn = (Button) convertView;
        }

        btn.setId(position);
        btn.setBackgroundResource(R.drawable.undiscovered);
        btn.setOnClickListener(new MyOnClickListener(position));
        return btn;
    }
}

这是我的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.gabriel.minesweeper.GameActivity">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:id="@+id/GameTextview"/>

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:stretchMode="columnWidth"
        android:gravity="center"/>


</LinearLayout>

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

使用ImageButton类(扩展Button),我们可以得到您想要的内容......(滚动到底部查看完整的代码示例)

获取父View的宽度,GridView

double parentWidth = ((MainActivity) mContext).findViewById(R.id.gridview).getWidth();

获取按钮图像尺寸

double width = button.getDrawable().getIntrinsicWidth();
double height = button.getDrawable().getIntrinsicHeight();

计算X轴中比例缩放的缩放因子

对于比例缩放 scalex希望为= 1scaley想要成为父级{{1}的图像宽度与宽度之间的比率}}。我们计算如下:

View

使用比例因子

计算新尺寸
double scalex = parentWidth / parentWidth;
double scaley = parentWidth / width;

对于 square int newWidth = (int) (width * scalex); int newHeight = (int) (height * scaley); ,请使用以下代码:

ImageButton

ImageButton缩放类型

比例类型int newWidth = (int) parentWidth; int newHeight = (int) parentWidth; 可确保图像相对于CENTER_INSIDE显示在中央,并以完整尺寸显示而不会失真。

ImageButton

这就是一起:

button.setScaleType(ImageButton.ScaleType.CENTER_INSIDE);

Proportional Scaling