正如在我的标题gridview中,图像不适合所有屏幕.
在我的应用程序中,我有15个图像,它是标题,我想在所有屏幕尺寸的3列和5行格式显示它.
但我的Gridview不适合所有屏幕尺寸和图像,标题未正确对齐.
我已经在以下API级别测试了我的应用程序并得到了以下响应.
Reminders.java
public class Reminders extends Fragment {
private OnFragmentInteractionListener mListener;
private View rootView;
public Reminders() {
}
public static Reminders newInstance(String param1, String param2) {
Reminders fragment = new Reminders();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_reminders, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.photogridview);
gridView.setAdapter(new ImageAdapter(rootView.getContext())); // uses the view to get the context instead of getActivity().
return rootView;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
解决方法:
所以,问题在于你如何在这个方法中创建View,并且出现了一些问题:
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout linearlayout=new LinearLayout(mContext);
ImageView imageView = new ImageView(mContext);
TextView textView =new TextView(mContext);
textView.setGravity(Gravity.CENTER);
linearlayout.setOrientation(LinearLayout.VERTICAL);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new GridView.LayoutParams(230, 230));
textView.setText(mThumbTxt[position]);
linearlayout.addView(imageView);
linearlayout.addView(textView);
return linearlayout;
}
1)现在,你忽略了convertView,所以你在实例化View之前没有检查是否为null,从而浪费了GridViews的回收机制.
2)您将GridView.LayoutParams附加到嵌套在LinearLayout中的子视图. LinearLayout应该有GridView.LayoutParams,但LinearLayout的子节点应该有LinearLayout.LayoutParams.
3)layout_gravity和gravity之间有区别 – 你使用的是引力,对于LinearLayout来说,它不会像你想象的那样工作. (除非在此上下文中,您将TextView更改为match_parent的宽度,但那可能会使其他内容混乱)
我建议放弃动态创建并采用XML通胀方法.
标签:android-gridview,android
来源: https://codeday.me/bug/20190927/1824772.html