Array Adapter Load Images from Res Folder (Android App)

后端 未结 2 1715
臣服心动
臣服心动 2021-01-25 10:30

Am an Android newbiew. Am trying to load a bunch of images in my res/Drawable folder into a Gridview via an array adapter. unfortunately my the app crashes each time i try to vi

2条回答
  •  再見小時候
    2021-01-25 11:15

    Problem is that you try to assign String-type data to ImageView. The easiest way to fix it would be:

    1. Change resource array type to integer-array
    2. Instead of using simple ArrayAdapter with string data, use custom adapter like:

      class ImgAdapter extends BaseAdapter {
      @Override
      public int getCount() {
          return planets.length;
      }
      
      @Override
      public Integer getItem(final int position) {
          return planets[position];
      }
      
      @Override
      public long getItemId(final int position) {
          return position;
      }
      
      @Override
      public View getView(final int position, final View convertView, final ViewGroup parent) {
          final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_view_row, null);
          ImageView imageView = (ImageView) view.findViewById(R.id.imageGrid);
          imageView.setImageResource(getItem(position));
          return view;
      }
      }
      

    That is simple it. Last thing is to set new adapter to gridView

提交回复
热议问题