Android 如何从NavigationDrawer启动ItemFragment

Android 如何从NavigationDrawer启动ItemFragment,android,android-fragments,Android,Android Fragments,我有一个导航抽屉,在我的菜单活动中有不同的条目。导航抽屉有一个onNavigationDrawerItemSelect方法。我想开始一个新的全屏片段,其中有一个可滚动的项目列表。现在,在应用程序启动中,FragmentManager启动一个PlaceholderFragment,它似乎工作正常。我不知道如何从导航抽屉中的每个按钮开始新的itemsfragments,其中包含可滚动的项目列表 以下是MenuActivity类: package com.example.pymdev.pym_app;

我有一个
导航抽屉
,在我的
菜单活动
中有不同的条目。导航抽屉有一个
onNavigationDrawerItemSelect
方法。我想开始一个新的全屏片段,其中有一个可滚动的项目列表。现在,在应用程序启动中,
FragmentManager
启动一个
PlaceholderFragment
,它似乎工作正常。我不知道如何从导航抽屉中的每个按钮开始新的
itemsfragments
,其中包含可滚动的项目列表

以下是MenuActivity类:

package com.example.pymdev.pym_app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.login.LoginManager;


public class MenuActivity extends AppCompatActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        ItemFragment fragment;
        FragmentManager fragmentManager = getSupportFragmentManager();
        switch(position) {
            default:
            case 0: //Select cooler animations
                Toast.makeText(getApplicationContext(), "Pos0",
                        Toast.LENGTH_LONG).show();
                //fragment = new ItemFragment();
                break;
            case 1: //Send Text to cooler
                Toast.makeText(getApplicationContext(), "Pos1",
                        Toast.LENGTH_LONG).show();

                break;
            case 2: //Play Games on cooler
                Toast.makeText(getApplicationContext(), "Pos2",
                        Toast.LENGTH_LONG).show();

                break;
            case 3: //Manage friends access to cooler
                Toast.makeText(getApplicationContext(), "Pos3",
                        Toast.LENGTH_LONG).show();

                break;
            case 4: //Logout Procedure
                Toast.makeText(getApplicationContext(), "Pos4",
                        Toast.LENGTH_LONG).show();
                logoutProcedure();
                break;
            case 5: //Connect to cooler
                Toast.makeText(getApplicationContext(), "Pos5",
                        Toast.LENGTH_LONG).show();

                break;
        }

        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    /* Logout procedure executes when Logout is pressed in Navigation Drawer */
    public void logoutProcedure(){
                /* Logout from facebook */
        LoginManager.getInstance().logOut();
                /* Switch back to login screen */
        Intent i = new Intent(MenuActivity.this, LoginActivity.class);
        startActivity(i);
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                mTitle = getString(R.string.title_section5);
                break;
            case 6:
                mTitle = getString(R.string.title_section6);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.menu, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MenuActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}
下面是ItemFragment类:

package com.example.pymdev.pym_app;

import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.example.pymdev.pym_app.dummy.DummyContent;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Large screen devices (such as tablets) are supported by replacing the ListView
 * with a GridView.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener}
 * interface.
 */
public class ItemFragment extends Fragment implements AbsListView.OnItemClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private ListAdapter mAdapter;

    // TODO: Rename and change types of parameters
    public static ItemFragment newInstance(String param1, String param2) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // TODO: Change Adapter to display your content
        mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);

        // Set the adapter
        mListView = (AbsListView) view.findViewById(android.R.id.list);
        ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

        // Set OnItemClickListener so we can be notified on item clicks
        mListView.setOnItemClickListener(this);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
        }
    }

    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */
    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListView.getEmptyView();

        if (emptyView instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }

}
package com.example.pymdev.pym_应用程序;
导入android.app.Activity;
导入android.os.Bundle;
导入android.app.Fragment;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AbsListView;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.ListAdapter;
导入android.widget.TextView;
导入com.example.pymdev.pym_app.dummy.dummcontent;
/**
*表示项目列表的片段。
*

*通过替换ListView支持大屏幕设备(如平板电脑) *有一个网格视图。 *

*包含此片段的活动必须实现{@link OnFragmentInteractionListener} *接口。 */ 公共类ItemFragment扩展片段实现AbsListView.OnItemClickListener{ //TODO:重命名参数参数,选择匹配的名称 //片段初始化参数,例如ARG_ITEM_NUMBER 私有静态最终字符串ARG_PARAM1=“PARAM1”; 私有静态最终字符串ARG_PARAM2=“PARAM2”; //TODO:重命名和更改参数类型 私有字符串mParam1; 私有字符串mParam2; 私有OnFragmentInteractionListener mListener; /** *片段的ListView/GridView。 */ 私有AbsListView-mListView; /** *用于填充ListView/GridView的适配器 *观点。 */ 私有列表适配器mAdapter; //TODO:重命名和更改参数类型 公共静态ItemFragment newInstance(字符串param1,字符串param2){ ItemFragment=新的ItemFragment(); Bundle args=新Bundle(); args.putString(ARG_PARAM1,PARAM1); args.putString(ARG_PARAM2,PARAM2); fragment.setArguments(args); 返回片段; } /** *片段管理器实例化 *碎片(如屏幕方向改变时)。 */ 公共项目片段(){ } @凌驾 创建时的公共void(Bundle savedInstanceState){ super.onCreate(savedInstanceState); 如果(getArguments()!=null){ mParam1=getArguments().getString(ARG_PARAM1); mParam2=getArguments().getString(ARG_PARAM2); } //TODO:更改适配器以显示您的内容 mAdapter=newarrayadapter(getActivity(), android.R.layout.simple_list_item_1,android.R.id.text1,DummyContent.ITEMS); } @凌驾 创建视图上的公共视图(布局、充气机、视图组容器、, Bundle savedInstanceState){ 视图=充气机。充气(R.layout.fragment_项目,容器,错误); //设置适配器 mListView=(AbsListView)view.findviewbyd(android.R.id.list); ((AdapterView)mListView).setAdapter(mAdapter); //设置McClickListener,以便在单击项目时收到通知 mListView.setOnItemClickListener(此); 返回视图; } @凌驾 公共事务主任(活动){ 超级转速计(活动); 试一试{ mListener=(OnFragmentInteractionListener)活动; }catch(ClassCastException e){ 抛出新的ClassCastException(activity.toString() +“必须实现OnFragmentInteractionListener”); } } @凌驾 公共无效连接(){ super.onDetach(); mListener=null; } @凌驾 public void onItemClick(AdapterView父对象、视图、整型位置、长id){ if(null!=mListener){ //通知活动回调接口(活动,如果 //片段被附加到一个)上,表示已选择项目。 onFragmentInteraction(DummyContent.ITEMS.get(position.id)); } } /** *此片段的默认内容有一个文本视图,当 *列表为空。如果要更改文本,请调用此方法 *提供它应该使用的文本。 */ public void setEmptyText(字符序列emptyText){ View-emptyView=mListView.getEmptyView(); 如果(清空文本视图的视图实例){ ((TextView)emptyView.setText(emptyText); } } /** *此接口必须由包含以下内容的活动实现 *片段,以允许通信此片段中的交互 *该活动以及其中可能包含的其他片段 *活动。 *

*有关更多信息,请参阅Android培训课程。 */ FragmentInteractionListener上的公共接口{ //TODO:更新参数类型和名称 公共void onFragmentInteraction(字符串id); } }


像这样的呼叫开关

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    switch(position) {
        default:
        case 0: //Select cooler animations
            callFragment(fragmentManager, position);
            Toast.makeText(getApplicationContext(), "Pos0",
                    Toast.LENGTH_LONG).show();
            //fragment = new ItemFragment();
            break;
        case 1: //Send Text to cooler
            callFragment(fragmentManager, position);
            Toast.makeText(getApplicationContext(), "Pos1",
                    Toast.LENGTH_LONG).show();

            break;
        case 2: //Play Games on cooler
            callFragment(fragmentManager, position);
            Toast.makeText(getApplicationContext(), "Pos2",
                    Toast.LENGTH_LONG).show();

            break;
        case 3: //Manage friends access to cooler
            callFragment(fragmentManager, position);
            Toast.makeText(getApplicationContext(), "Pos3",
                    Toast.LENGTH_LONG).show();

            break;
        case 4: //Logout Procedure
            callFragment(fragmentManager, position);
            break;
        case 5: //Connect to cooler
            callFragment(fragmentManager, position);

            break;
    }
}
调用
ItemFragment
方法

    public void callFragment(FragmentManager fragmentManager,int position){
     fragmentManager.beginTransaction()
     .replace(R.id.container, ItemFragment.newInstance(position ,position+1))
     .commit();
}

您好,我尝试了您的解决方案,但
ItemFragment.newInstance(position,position+1))
需要字符串作为参数,而不是int.replace为this
ItemFragment.newInstance(position,String.valueOf(position+1))