使用NavigatorDrawer时,如何从一个片段或活动更改为另一个片段或活动?

时间:2014-07-04 00:48:52

标签: android android-intent android-activity android-fragments

抱歉,我的问题比我提出的要复杂得多。我是Java和Android的新手,整个NavigationDrawer事情都让我失望,但我决心弄明白。我使用导航抽屉示例从Android下载了示例代码,我已删除并添加了一些小的更改以适应首选项。基本上,使用提供给我的代码,我无法弄清楚如何更改为不同的活动/片段。我应该使用像示例所示的其他片段,还是需要创建一个扩展intent并创建相应xml布局的新Java类?一旦确定了,我是否在片段类中创建了一个switch case,它是为了循环通过相应的片段/活动而创建的?或者我在selectItem()方法中放置一个开关案例?我已经在这个问题上工作了8天,最后我决定在耗尽所有资源后寻求帮助。谢谢你的帮助。同样,我不是在寻找代表我的人,我只需要帮助理解我提出的问题以及我的代码需要放在哪里。

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] choices;

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

        mTitle = mDrawerTitle = getTitle();
        choices = getResources().getStringArray(R.array.choices_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, choices));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        /*
        switch(item.getItemId()) {
            case R.id.action_websearch:
                // create intent to perform web search for this planet
                Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
                // catch event that there's no activity to handle intent
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivity(intent);
                } else {
                    Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }*/
        return super.onOptionsItemSelected(item);
    }

    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);

        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new ChoicesFragment();
        Bundle args = new Bundle();
        args.putInt(ChoicesFragment.ARG_CHOICES_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(choices[position]);
        mDrawerLayout.closeDrawer(mDrawerList);

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggle
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows its appropriate layout
     */
    public static class ChoicesFragment extends Fragment {
        public static final String ARG_CHOICES_NUMBER = "planet_number";

        public ChoicesFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.image_view_fragment, container, false);
            int i = getArguments().getInt(ARG_CHOICES_NUMBER);
            String available_choices = getResources().getStringArray(R.array.choices_array)[i];

            int imageId = getResources().getIdentifier(available_choices.toLowerCase(Locale.getDefault()),
                    "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(available_choices);
            return rootView;
        }
    }// end ChoicesFragment class
}// end MainActivity    

2 个答案:

答案 0 :(得分:1)

查看您发布的代码(我无法编译并立即尝试),我相信示例的目的是在导航抽屉上选择选项时使用片段。然后你会在selectItem()中放一个case语句来确定应该显示哪个片段。

例如,如果您有两个选择(例如&#34;显示红色&#34;和&#34;显示蓝色&#34;),您将创建一个&#34; RedFragment&#34;课程延伸&#34; ChoicesFragment&#34;,以及&#34; BlueFragment&#34;课程延伸&#34; ChoicesFragment&#34;。他们每个人都会使用自己的XML布局。然后,您可以在onCreate()方法中为每个对象创建一个片段对象(例如&#34; redFragment&#34;&#34; blueFragment&#34;)。

然后,在selectItem()方法中,你有一个if / case语句来说明position是否为0,那么你将显示红色片段:

...
fragmentManager.beginTransaction().replace(R.id.content_frame, redFragment).commit();
...

和蓝色片段类似。

HTH。

答案 1 :(得分:0)

看起来您在理解抽象级别时遇到了一些问题,我会尽力帮助解决这个问题。

活动是您应用的最高入门点。最好的方法是使用片段而不是活动,因为片段处于较低的抽象层次,片段只是活动的一部分。

在片段中构建所有视图,然后将它们放在一个活动上,除非您真的需要更高级别的抽象,具体取决于您的应用程序的功能。

我认为没有必要创建扩展意图等的类等。

我想将导航抽屉添加为片段并将其放入活动中,应用程序的其余部分应该是导航抽屉处理的片段。

或者导航抽屉可以是活动的一部分,也可以是依赖此活动的其余视图片段。

希望这有助于清除你的想法..抱歉不共享代码..祝你好运