如何使用导航抽屉避免 android 中的片段重叠

how to avoid Fragments Overlap in android with Navigation Drawer

我正在创建一个应用程序,我在其中使用带有导航抽屉的首选项片段我的问题是我创建了导航抽屉并在其中添加了一些菜单项,我想在其中加载首选项片段作为第一个元素当应用程序 loads.it 像我一样显示时。当我更改选项时 I-e.when 我正在更改抽屉菜单选项,例如第二个元素,抽屉菜单中的第一个视图不会替换为第二个,它与第一个 [= 重叠17=]

我的抽屉导航xml如下

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.koteswara.wise.NavigationDrawerMainActivity" >

  <FrameLayout
        android:id="@+id/container"

        android:layout_width="match_parent"
        android:layout_height="match_parent" />
<LinearLayout 
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:orientation="vertical" 
        android:layout_gravity="start" >
 <ListView 
     android:id="@+id/drawer_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    tools:context="com.koteswara.wise.NavigationDrawerFragment" />
 </LinearLayout>

</android.support.v4.widget.DrawerLayout>

我喜欢的片段是这样的

public class AutoAnswerPreferenceActivity extends PreferenceFragment implements OnSharedPreferenceChangeListener { 
    private AutoAnswerNotifier mNotifier;
    @Override
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
        mNotifier = new AutoAnswerNotifier(getActivity()); 
        mNotifier.updateNotification();
        SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences();
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);


        }

    @Override
    public void onDestroy() { 
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        super.onDestroy();
        }
    @Override 
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { 
        if (key.equals("enabled")) { 
            mNotifier.updateNotification();
            }  
        } 

    } 

我正在添加以加载 PreferenceFragment 的片段 class 是

public class AutoAnswarFragment extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
         getActivity().getFragmentManager().beginTransaction().replace(R.id.container, new AutoAnswerPreferenceActivity()) .commit();


    }

导航抽屉class其中show fragment方法是

protected void showFragment(int position) {
        // TODO Auto-generated method stub
        Fragment fragment = null;

        switch (position) {
        case 0:
            fragment = new  AutoAnswarFragment();
            break;
        case 1:
             fragment = new Tab2();
            break;
        case 2:
            // fragment = new BhajanaFragment();
            break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment).commit();

            // update selected item and title, then close the drawer
            // mDrawerList.setItemChecked(position, true);
            // mDrawerList.setSelection(position);
            mTitle = mDrawer_title[position];
            // mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            // Log.e("MainActivity", "Error in creating fragment");
        }
    }


}

如果我将调用不同于下面的首选项片段的片段,它会起作用,请帮助我

public class Tab1 extends Fragment {

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

我正在努力为它清除解决方案,请任何人解决它,请告诉我解决方案。我将非常感谢,请帮助我

经过这么多天的研究和网络搜索,我找到了解决上述问题的解决方案,它对我来说效果很好,网络上有一个 link 作为 http://www.michenux.net/android-preferencefragmentcompat-906.html 在这个我找到了一个示例 apk 和有关 apk 的源代码。因为这个 apk 有一个功能,因为它解决了我的问题。我清除了导入时出现的源代码错误,之后我将库添加到我的项目中。我使用了 PreferenceCompatFragment 而不是 PreferenceFragmentCompat,它解决了我的问题,如果有人需要帮助,它也可以帮助他们,所以我发布了我对上述问题的解决方案。我感谢所有帮助过我的人以及对上述问题给出了一些宝贵建议的人。 下面 class 下面我使用了而不是 v7 支持库的 PreferenceFragmentCompat

public abstract class PreferenceCompatFragment extends Fragment {

    private static final int FIRST_REQUEST_CODE = 100;
    private static final int MSG_BIND_PREFERENCES = 1;
    private static final String PREFERENCES_TAG = "android:preferences";
    private boolean mHavePrefs;
    private boolean mInitDone;
    private ListView mList;
    private PreferenceManager mPreferenceManager;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MSG_BIND_PREFERENCES:
                    bindPreferences();
                    break;
            }
        }
    };

    final private Runnable mRequestFocus = new Runnable() {
        public void run() {
            mList.focusableViewAvailable(mList);
        }
    };

    private void bindPreferences() {
        PreferenceScreen localPreferenceScreen = getPreferenceScreen();
        if (localPreferenceScreen != null) {
            ListView localListView = getListView();
            localPreferenceScreen.bind(localListView);
        }
    }

    private void ensureList() {
        if (mList == null) {
            View view = getView();
            if (view == null) {
                throw new IllegalStateException("Content view not yet created");
            }

            View listView = view.findViewById(android.R.id.list);
            if (!(listView instanceof ListView)) {
                throw new RuntimeException("Content has view with id attribute 'android.R.id.list' that is not a ListView class");
            }

            mList = (ListView)listView;
            if (mList == null) {
                throw new RuntimeException("Your content must have a ListView whose id attribute is 'android.R.id.list'");
            }

            mHandler.post(mRequestFocus);
        }
    }

    private void postBindPreferences() {
        if (mHandler.hasMessages(MSG_BIND_PREFERENCES)) {
            mHandler.obtainMessage(MSG_BIND_PREFERENCES).sendToTarget();
        }
    }

    private void requirePreferenceManager() {
        if (this.mPreferenceManager == null) {
            throw new RuntimeException("This should be called after super.onCreate.");
        }
    }

    public void addPreferencesFromIntent(Intent intent) {
        requirePreferenceManager();
        PreferenceScreen screen = inflateFromIntent(intent, getPreferenceScreen());
        setPreferenceScreen(screen);
    }

    public void addPreferencesFromResource(int resId) {
        requirePreferenceManager();
        PreferenceScreen screen = inflateFromResource(getActivity(), resId, getPreferenceScreen());
        setPreferenceScreen(screen);
    }

    public Preference findPreference(CharSequence key) {
        if (mPreferenceManager == null) {
            return null;
        }
        return mPreferenceManager.findPreference(key);
    }

    public ListView getListView() {
        ensureList();
        return mList;
    }

    public PreferenceManager getPreferenceManager() {
        return mPreferenceManager;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getListView().setScrollBarStyle(0);
        if (mHavePrefs) {
            bindPreferences();
        }
        mInitDone = true;
        if (savedInstanceState != null) {
            Bundle localBundle = savedInstanceState.getBundle(PREFERENCES_TAG);
            if (localBundle != null) {
                PreferenceScreen screen = getPreferenceScreen();
                if (screen != null) {
                    screen.restoreHierarchyState(localBundle);
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        dispatchActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        mPreferenceManager = createPreferenceManager();
    }

    @Override
    public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
        return paramLayoutInflater.inflate(R.layout.preference_list_content, paramViewGroup, false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispatchActivityDestroy();
    }

    @Override
    public void onDestroyView() {
        mList = null;
        mHandler.removeCallbacks(mRequestFocus);
        mHandler.removeMessages(MSG_BIND_PREFERENCES);
        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(Bundle bundle) {
        super.onSaveInstanceState(bundle);
        PreferenceScreen screen = getPreferenceScreen();
        if (screen != null) {
            Bundle localBundle = new Bundle();
            screen.saveHierarchyState(localBundle);
            bundle.putBundle(PREFERENCES_TAG, localBundle);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        dispatchActivityStop();
    }

    /** Access methods with visibility private **/

    private PreferenceManager createPreferenceManager() {
        try {
            Constructor<PreferenceManager> c = PreferenceManager.class.getDeclaredConstructor(Activity.class, int.class);
            c.setAccessible(true);
            return c.newInstance(this.getActivity(), FIRST_REQUEST_CODE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private PreferenceScreen getPreferenceScreen() {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("getPreferenceScreen");
            m.setAccessible(true);
            return (PreferenceScreen) m.invoke(mPreferenceManager);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void setPreferenceScreen(PreferenceScreen preferenceScreen) {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("setPreferences", PreferenceScreen.class);
            m.setAccessible(true);
            boolean result = (Boolean) m.invoke(mPreferenceManager, preferenceScreen);
            if (result && preferenceScreen != null) {
                mHavePrefs = true;
                if (mInitDone) {
                    postBindPreferences();
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void dispatchActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityResult", int.class, int.class, Intent.class);
            m.setAccessible(true);
            m.invoke(mPreferenceManager, requestCode, resultCode, data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void dispatchActivityDestroy() {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityDestroy");
            m.setAccessible(true);
            m.invoke(mPreferenceManager);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void dispatchActivityStop() {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("dispatchActivityStop");
            m.setAccessible(true);
            m.invoke(mPreferenceManager);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private void setFragment(PreferenceFragment preferenceFragment) {
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("setFragment", PreferenceFragment.class);
            m.setAccessible(true);
            m.invoke(mPreferenceManager, preferenceFragment);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public PreferenceScreen inflateFromResource(Context context, int resId, PreferenceScreen rootPreferences) {
        PreferenceScreen preferenceScreen ;
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class);
            m.setAccessible(true);
            preferenceScreen = (PreferenceScreen) m.invoke(mPreferenceManager, context, resId, rootPreferences);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return preferenceScreen;
    }

    public PreferenceScreen inflateFromIntent(Intent queryIntent, PreferenceScreen rootPreferences) {
        PreferenceScreen preferenceScreen ;
        try {
            Method m = PreferenceManager.class.getDeclaredMethod("inflateFromIntent", Intent.class, PreferenceScreen.class);
            m.setAccessible(true);
            preferenceScreen = (PreferenceScreen) m.invoke(mPreferenceManager, queryIntent, rootPreferences);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return preferenceScreen;
    }
}

确保所有片段的根布局都具有

android:background="@color/your_favorite_color"

这样他们就可以在下面隐藏其他片段。