我有一个gridview,从适配器获得4个imageviews,我想让他们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添加更多行,它将工作。
是这样的:
拉/幻数
当我使用GridView。AUTO_FIT在高度上它会增加很多无用的空间我在右边得到一个滚动条,像这样:
垂直无用空间
我尝试了几种配置和拉伸,但似乎都不起作用。任何方法来实现我想要的编程没有xml?
试试这个:gridView.setNumColumns (2);