解决ViewPager中添加fragment,fragment中使用GridView控件不显示,控件重叠的问题
程序员文章站
2022-05-26 09:29:19
...
一个主Activity中使用ViewPager,ViewPager中添加多个Fragment,在Fragment中使用GridView时控件不显示,或是显示重叠的问题解决:
首先排查viewpager设置了适配器,并且适配器中有数据,有一种情况是gridview的item过小,被标题栏挡住了。可以设置图片宽高为具体值比如200dp。这样就可以确定是否被标题栏挡住。
下面展示gridview数据适配的使用方法:
继承BaseAdapter,重点是getView方法,和列表类适配器类似
public class ImageAdapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
String[] names = {"首页", "首页", "首页", "首页", "首页", "首页", "首页", "首页"};
int[] icons = {R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher
, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher, R.mipmap.ic_launcher};
public ImageAdapter(Context context) {
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return icons.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_grid_view, null);
holder = new ViewHolder();
holder.gvImage = convertView.findViewById(R.id.id_gv_img);
holder.gvName = convertView.findViewById(R.id.id_gv_name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.gvName.setText(names[position]);
holder.gvImage.setImageResource(icons[position]);
return convertView;
}
static class ViewHolder {
public ImageView gvImage;
public TextView gvName;
}
}
使用:
如果是在fragment中,要在onCreateView中设置
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
id_GridView = view.findViewById(R.id.id_GridView);
id_GridView.setAdapter(new ImageAdapter(getActivity()));
id_GridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "点击了第" + position + "个", Toast.LENGTH_SHORT).show();
}
});
return view;
}
此时可以看到item会显示出来,但仍有item重叠的情况,比如item叠加在标题栏上
此问题的解决方案:
将主布局由ConstraintLayout改为LinearLayout即可,原因是因为ConstraintLayout没有使用熟练,缺少设置项。