0

在我的MainActivity.java课堂上,我有一个名为的起始片段MainScreenFragment.java,它按预期工作。但是,当用户单击我的第二​​个菜单项时,我drawer-layout将其替换为另一个名为UserBoxGLBFragment.java. 通过使用 Log.d(); 在里面调用onCreateViewonViewCreated我发布了 UserBoxGLBFragment 的方法根本不会被调用(这可能是我看不到它的内容的原因)。你能帮我弄清楚为什么会这样吗?以下是课程:

MainActivity.java:

public class MainActivity extends AppCompatActivity {

private Toolbar mToolbar;

// NavMenu member vars
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle mToggle; // Button for toggling the side menu

// Keeps the position of the previously selected menu item(0 : Home)
int position = 0;

// Declaring our dialog
ImportantDialogFragment dialogFragment = new ImportantDialogFragment();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Showing the disclaimer dialog every time the app starts
    dialogFragment.show(getSupportFragmentManager(),"IMPORTANT_NOTICE");

    mDrawerLayout = findViewById(R.id.drawerLayout);
    navigationView = findViewById(R.id.nav_view);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.drawer_open,R.string.drawer_closed); // Instantiating our button


    mToolbar = findViewById(R.id.navActionBar);
    setSupportActionBar(mToolbar); // check quick doq
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    mToolbar.setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Sets the default selected menu item, to the Home item
    navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);

    // Used to help on check and uncheck menu items when the user clicks on them
    final List<MenuItem> items = new ArrayList<>();
    Menu menu;
    menu = navigationView.getMenu();

    // Fill the list with all the menu items
    for(int i=0; i<menu.size();i++) {
        items.add(menu.getItem(i));
    }

   // Toast.makeText(this, "size:" + items.size(), Toast.LENGTH_SHORT).show();

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

    mDrawerLayout.addDrawerListener(mToggle);
    // Set the hamburger icon's color
    mToggle.getDrawerArrowDrawable().setColor(getResources().getColor(R.color.NavActionBarTextColor));
    mToggle.syncState();
}

// When an item from the Action Bar gets tapped, then...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return mToggle.onOptionsItemSelected(item) || onOptionsItemSelected(item);
}

private String[] emails = {"SPDesignsOfficial@outlook.com"};

/**
 * Send an email to the @adress with a @subject
 * @param addresses The email adress(es) to send the email to
 * @param subject The email's subject
 */
public void composeEmail(String[] addresses, String subject, String message) {
    Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT,message);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}
}

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


UserBoxGLBFragment fragment = new UserBoxGLBFragment();
private void addSelectedCardToGlobalUserBox(int position) {
    ImageAdapter imageAdapter = new ImageAdapter(getContext());
    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();
}

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

}

用户框GLBFragment.java:

public class UserBoxGLBFragment extends Fragment {

GridView globalGridView;
UserBoxGlbImageAdapter adapter = new UserBoxGlbImageAdapter(getContext());

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

1 回答 1

-1

在onNavigationItemSelected中附加调试器case R.id.nav_UserBoxGLB:此方法是否被调用。

并查看 NavigationView 菜单是否具有 nav_UserBoxGLB id。

并确保您的UserBoxGLBFragmentis 扩展android.support.v4.fragment.

于 2017-11-28T11:47:39.420 回答