图像适配器无法初始化图像视图

Image Adapter not able to initialize image Views

我有一个包含 gridView 的片段,我正在使用自定义 ImageAdapter class 将 imageView 设置为网格的项目并使用我的 drawables 中的图像对其进行初始化文件夹。但是,无论我尝试了什么,imageView 都没有显示所需的图像。你能帮我找出问题所在吗?这是我的代码:

已完全更新

在下面的 class 中,当用户单击在我的 firstFragment class 中创建的上下文菜单的第一项时,我得到一个整数值表示一个可绘制文件并将其传递到我的 UserBoxGLBFragment.java class 以进行进一步处理:

MainScreenFragment.java:

public class MainScreenFragment extends Fragment {

// Main Grid View
GridView gridView;

public MainScreenFragment() {
    // Required empty public constructor
}

// Create a Context Menu when an item in the GridView is long-pressed
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Card Options");
    //AdapterView.AdapterContextMenuInfo cmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
    menu.add(1,v.getId(),0, "Add Card to GLB");
    menu.add(2,v.getId(),0,"Add Card to JP");
}

// When an item in the context menu gets selected, call a method
@Override
public boolean onContextItemSelected(MenuItem item) {

    // Get some extra info about the contextMenu
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    int position = info.position; // clicked view's position

    if(item.getTitle().equals("Add Card to GLB")) {
        addCardMessage(position, "added to GLB");
        addSelectedCardToGlobalUserBox(position);
    } else if (item.getTitle().equals("Add Card to JP")) {
        addCardMessage(position , "added to JP");
    } else
    {
        return false;
    }
    return false;
}

/**
 * Creates a snackbar message, telling the user which card was added to which box
 * @param id The position of the chosen card
 * @param text Defines into which User Box the card was added
 */
private void addCardMessage(int id, String text) {
      final Snackbar snackbar = Snackbar.make(gridView, id + " " + text ,Snackbar.LENGTH_LONG);

      snackbar.setAction("Dismiss", new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            snackbar.dismiss();
        }
    });
    snackbar.setActionTextColor(Color.MAGENTA);
    snackbar.show();
}


private void addSelectedCardToGlobalUserBox(int position) {
    ImageAdapter imageAdapter = new ImageAdapter(getContext());

    UserBoxGLBFragment fragment = ((MainActivity)getActivity()).getMyFragment();

    if (fragment != null){
        fragment.addInteger(imageAdapter.getmThumbIds(0)); // pass the Drawable's Integer value to the fragmnet
    } else {
        Log.d("CHECK: " , "Fragment is NULL");
    }

    Toast.makeText(getActivity(), "Selected icon: " + imageAdapter.getmThumbIds(position), Toast.LENGTH_SHORT).show();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_main_screen, container, false);

    gridView = view.findViewById(R.id.gridViewLayout);
    gridView.setAdapter(new ImageAdapter(getContext())); // used to set the contents of the GridView-in this case images-
    registerForContextMenu(gridView);

    // When an item from the GridView gets clicked
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Create a new Intent...
            Toast.makeText(getActivity(), "Position: " + position, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getContext(),CardViewActivity.class);
            intent.putExtra("Card Index",position);
            intent.putExtra("SCREEN_WIDTH",1080);
            startActivity(intent);
        }
    });
    return view;
}
}

现在 class 设置网格的适配器并传递新接收到的应该在适配器中使用的 Integer 来更新 imageView

UserBoxGLBFragment.java:

public class UserBoxGLBFragment extends Fragment {

GridView globalGridView;
UserBoxGlbImageAdapter adapter;

public UserBoxGLBFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    Log.d("onCreateView:" , "onCreateView called successfully!");
    adapter = new UserBoxGlbImageAdapter(this.getContext());
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
    return view;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    globalGridView = view.findViewById(R.id.userBoxGlbGridView);
    globalGridView.setAdapter(adapter);
    Log.d("OnViewCreated:" , "OnViewCreated called successfully!");
}

public void addInteger(Integer integer) {
    adapter.addDrawableToList(integer);
}
}

最后,这是 UserBoxGLBFragment 的图像适配器 class,它用于-据推测-用新的整数值更新 gridView 内的 imageView

UserBoxGLBImageAdapter.java:

public class UserBoxGlbImageAdapter extends BaseAdapter {

    private Context mContext;

    private List<Integer> mGLBIcons = new ArrayList<>();

    public UserBoxGlbImageAdapter(Context c) {
        mContext = c;
    }

    public List<Integer> getIcons() {
        return mGLBIcons;
    }

    @Override
    public int getCount() {
       return mGLBIcons.size();
    }

    @Override
    public Object getItem(int i) {
        return mGLBIcons.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        // If it's not recycled, initialize some attributes
        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }
         //Drawable drbl = mContext.getResources().getDrawable(mGLBIcons.get(0));
        Toast.makeText(mContext, "Size:" + getCount(), Toast.LENGTH_SHORT).show();
        Log.d("mGLBIcons List", "[0] element: " + getIcons().get(0));
        imageView.setImageResource(getIcons().get(0));
        return imageView;
    }

    public void addDrawableToList(Integer integer) {
        Log.d("addDrawbaleToList clled", "Integer used: " + integer + " GLBIcons size: " + mGLBIcons.size());
        mGLBIcons.add(integer);
        notifyDataSetChanged();
    }
}

编辑 MainActivity.java[处理片段的部分在activity]内发生变化:

        // Set the default starting screen to the mainScreen
    FragmentManager startingScreenManager = getSupportFragmentManager();
    FragmentTransaction startingScreenTransaction = startingScreenManager.beginTransaction();

    MainScreenFragment fragment = new MainScreenFragment();
    startingScreenTransaction.add(R.id.FrameLayoutContainer, fragment);
    startingScreenTransaction.commit();

    final UserBoxGLBFragment glbFragment = new UserBoxGLBFragment();
    // When an item inside the NavView gets clicked, then handle the event...
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        // Initializing these vars again for use in this inner class
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Replace the main Fragment in this activity based on the menu item selected
            switch (item.getItemId()) {
                case R.id.nav_home:
                    MainScreenFragment mainScreenFragment = new MainScreenFragment();
                    fragmentTransaction.replace(R.id.FrameLayoutContainer,mainScreenFragment);
                    fragmentTransaction.commit();
                    break;
                case R.id.nav_UserBoxGLB:
                    //UserBoxGLBFragment glbFragment = new UserBoxGLBFragment();
                    Log.d("UserBoxGLB:" , "Called");
                    fragmentTransaction.replace(R.id.FrameLayoutContainer,glbFragment);
                    fragmentTransaction.commit();
                    break;
                case R.id.nav_UserBoxJP:
                    break;
                case R.id.nav_events:
                    Toast.makeText(MainActivity.this, "Events are not available yet! Sorry", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.nav_feedback:
                    composeEmail(emails,"Feedback", "[Your message here]");
                    break;
                case R.id.nav_contact_us:
                    composeEmail(emails,"Contact Us", "[Your message here]");
                    break;
                case R.id.nav_website:
                    // Open the website's URL in a browser window
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse("http://www.google.com"));
                    startActivity(intent);
                    break;
                case R.id.nav_about:
                    Intent aboutIntent = new Intent(MainActivity.this, AboutPageActivity.class);
                    startActivity(aboutIntent);
                    break;
                default:
                    return onNavigationItemSelected(item);
            }
            items.get(position).setChecked(false);
            item.setChecked(true);
            mDrawerLayout.closeDrawers();
            return false;
        }
    });

getMyFragment() 在 MainActivity.java:

    public UserBoxGLBFragment getMyFragment(){
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.FrameLayoutContainer);
    if (fragment instanceof UserBoxGLBFragment){
        return (UserBoxGLBFragment)fragment;
    }
    return null;

}

我很确定我的代码可以清理得更多,但我真的想先了解我在这里缺少的逻辑部分

@Override
public int getCount() {
    return 0;
}

这应该returniconsList.size()

@Override
public Object getItem(int i) {
    return null;
}

这应该returniconsList.get(i)

在您的 FragmentImageAdapter.java 文件中:

@Override
 public int getCount() {
    return mGLBIcons.size;
}

当您在 getCount() 上 return 0 时,适配器接收 0 作为项目数,因此不会显示任何内容。取而代之的是 return 您传递的数组的大小。

在您的 MainActivity 上创建一个方法来获取您需要的片段:

    public UserBoxGLBFragment getMyFragment(){
          Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.FrameLayoutContainer); 
                if (fragment instanceof UserBoxGLBFragment){
                    return (UserBoxGLBFragment)fragment;
                }
                return null;

    }

从您的片段中调用该方法

    private void addSelectedCardToGlobalUserBox(int position) {
        ImageAdapter imageAdapter = new ImageAdapter(getContext());

        UserBoxGLBFragment fragment = ((MainActivity)getActivity()).getMyFragment();

        if (fragment != null){
            fragment.addInteger(imageAdapter.getmThumbIds(0)); // pass the Drawable's Integer value to the fragmnet
        }

        Toast.makeText(getActivity(), "Selected icon: " + imageAdapter.getmThumbIds(position), Toast.LENGTH_SHORT).show();
    }

将您的适配器实例移到 onCreateView 中:

    UserBoxGlbImageAdapter adapter; 

    public UserBoxGLBFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("OnViewCreated:" , "OnViewCreated called successfully!");
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
        adapter = new UserBoxGlbImageAdapter(getActivity());

        return view;
    }