簡體   English   中英

片段onCreateView等方法不會被調用

[英]Fragment onCreateView etc. methods don't get called

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

}

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

在情況R.id.nav_UserBoxGLB處的R.id.nav_UserBoxGLB附加調試器:此方法是否獲得調用。

並查看NavigationView菜單是否具有nav_UserBoxGLB ID。

並確保您的UserBoxGLBFragmentandroid.support.v4.fragment.擴展android.support.v4.fragment.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM