Gridlayout with 2x2 imageview android

时间:2016-08-29 09:57:14

标签: java android user-interface gridview imageview

我有一个gridview,从适配器获取4个图像视图,我想让它们2x2调整大小并安装在我的屏幕上。

这是代码:

@Override
protected View createQuizContentView() {
    mAnswerView = new GridView(getContext());

    StateListDrawable selector = new StateListDrawable();
    selector.addState(new int[]{android.R.attr.state_pressed}, new ColorDrawable(Color.LTGRAY));
    selector.addState(new int[]{-android.R.attr.state_pressed}, new ColorDrawable(Color.WHITE));

    mAnswerView.setSelector(selector);
    //mAnswerView.setSelector(R.drawable.selector_button);

    mAnswerView.setNumColumns(2);
    mAnswerView.setAdapter(new OptionsQuizAdapter(getQuiz().getOptions(),
            R.layout.imgitem_answer));


    mAnswerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mAnswered = position;
            allowAnswers(mAnswerView,position);
        }
    });
    return mAnswerView;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        convertView = inflater.inflate(mLayoutId, parent, false);
    }
    final ImageView imageView;
    String text = getText(position);
    Context context = parent.getContext();

    Resources resources = context.getResources();

    String stripped = text.replace("-", "");
    final int resourceId = resources.getIdentifier(stripped, "drawable",
            context.getPackageName());

    Drawable d = ContextCompat.getDrawable(context, resourceId);

    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int height = size.y;

    double dviewheight = height/3.32;
    int viewheight = (int)dviewheight;

    imageView = (ImageView) convertView;
    imageView.setPadding(64, 64, 64, 64);

    convertView.setLayoutParams(newGridView.LayoutParams(GridView.AUTO_FIT, viewheight));

    imageView.setImageDrawable(d);

    return imageView;
}

目前我在gridview中设置imageview的高度,通过获取屏幕大小并将其划分,在大多数设备分辨率下工作正常但是我仍然希望更加动态的解决方案,如果我添加更多行, gridview。

它的外观如下:

Screensize/magic number

当我在高度上使用GridView.AUTO_FIT时会增加很多无用的空间,我会在右边看到一个滚动条:

Useless space vertically

我尝试了几种配置和延伸,但似乎都没有。有没有办法在没有xml的情况下以编程方式实现我想要的东西?

1 个答案:

答案 0 :(得分:1)

试试这个:          gridView.setNumColumns(2);