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



我有一个包含GridView的片段,我使用自定义ImageDapter类将imageView设置为GRID项目,并用drawables文件夹中的图像初始化它。但是,无论我尝试过什么,ImageView都不会出现所需的图像。您能帮我找出问题吗?这是我的代码:

完全更新

在下面的类中,当用户单击我的firstFragment类中创建的上下文菜单的第一个项目时,我将获得一个代表可绘制文件的整数值,并将其传递到我的Userboxglbfragment.java类中处理:

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;
}
}

现在,此类设置了网格的适配器,并通过适配器中应使用的新收到的整数来更新ImageView(s)

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);
}
}

最后,这是用户boxglbfragment的映像适配器类,用于-supsposed-使用新的整数值

更新GridView内部的imageView

userboxglbbbimageadapter.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 [处理活动内部片段的变化的部分]:

        // 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;
        }
    });

mainActivity.java中的getMyFragment():

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

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

在您的主activity上创建一种方法,以获取所需的片段:

    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;
    }
@Override
public int getCount() {
    return 0;
}

这应该返回iconsList.size()

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

这应该返回iconsList.get(i)

在您的fragmentimageadapter.java文件中:

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

当您在getCount()上返回0时,适配器将接收0作为项目数,因此不会显示任何内容。而是返回您通过的数组的大小。

最新更新