如何使用活动开关创建菜单



如何使用活动切换器在Android上创建菜单,而不是每次使用意图都重绘它?我尝试使用ViewFlipper,但我想以编程方式更改视图。这是我想切换到的活动类。

You can make same thing using fragments instead of activity.
Edit: sample code to see full sample visit http://www.android4devs.com/2015/06/navigation-view-material-design-support.html
public class MainActivity extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initializing Toolbar and setting it as the actionbar
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigation_view);
    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        // This method will trigger on item Click of navigation menu
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not make it in checked state
            if(menuItem.isChecked()) menuItem.setChecked(false);
            else menuItem.setChecked(true);
            //Closing drawer on item click
            drawerLayout.closeDrawers();
            //Check to see which item was being clicked and perform appropriate action
            switch (menuItem.getItemId()){

                //Replacing the main content with ContentFragment Which is our Inbox View;
                case R.id.inbox:
                    Toast.makeText(getApplicationContext(),"Inbox Selected",Toast.LENGTH_SHORT).show();
                    InboxFragment inboxFragment = new InboxFragment();
                    addFragment(inboxFragment);
                    return true;
                // For rest of the options we just show a toast on click
                case R.id.starred:
                    Toast.makeText(getApplicationContext(),"Stared Selected",Toast.LENGTH_SHORT).show();
                    StarredFragment starredFragment = new StarredFragment();
                    addFragment(starredFragment);
                    return true;
    }
        }
    });

}

public void addFragment(Fragment fragment){
    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame,fragment); // you can use add but in that case previous fragment is visible so better approach is to use replace
    fragmentTransaction.commit();
}

}

最新更新