简体   繁体   English

如何使用导航抽屉避免Android中的碎片重叠

[英]how to avoid Fragments Overlap in android with Navigation Drawer

i am creating a application in which i am using preference Fragment with navigation Drawer my problem is i am created navigation Drawer and in which i am added some menu item in which i want to load the preference Fragment as a first element when the app loads.it is does as i don to display.我正在创建一个应用程序,我在其中使用带有导航抽屉的首选项 Fragment 我的问题是我创建了导航抽屉,并在其中添加了一些菜单项,我想在应用程序加载时将首选项 Fragment 作为第一个元素加载。它就像我不显示的那样。 when i am changing the options Ie.when i am changing the drawer menu options like second element the in the drawer menu fist view is not replacing with the second,it is overlapping an the first当我更改选项时,即当我更改抽屉菜单选项(如第二个元素)时,抽屉菜单的第一个视图没有替换为第二个,它与第一个重叠在此处输入图片说明

my navigation drawer xml is as follow我的导航抽屉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>

my preference fragment is like this我的偏好片段是这样的

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

    } 

my fragment class which is adding to load the PreferenceFragment is我正在添加以加载 PreferenceFragment 的片段类是

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();


    }

the navigation Drawer class in which show fragment method is显示片段方法所在的导航抽屉类

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


}

if i will call the fragment other than the preference Fragment like below it will works please help me如果我将调用除首选项片段以外的片段,如下所示,它会起作用,请帮助我

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

i am struggling to clear the solution for it please any body solve it and please tell me the solution .i will be the thank full please help me我正在努力清除它的解决方案,请任何机构解决它,请告诉我解决方案。我将非常感谢请帮助我

Be sure the root layout of all your fragments are having确保所有片段的根布局都具有

android:background="@color/your_favorite_color" android:background="@color/your_favorite_color"

In that way they will be hiding other fragments below.这样,他们将隐藏下面的其他片段。

on so many days of research and searching on the web i have found a solution its working fine for me for the above problem there is a link on the web as http://www.michenux.net/android-preferencefragmentcompat-906.html in this i found a sample apk and a source code regarding the apk .经过这么多天的研究和在网上搜索,我找到了一个解决方案,它对我来说很好解决上述问题,网上有一个链接http://www.michenux.net/android-preferencefragmentcompat-906.html在此我找到了一个示例 apk 和一个关于 apk 的源代码。 as this apk has a functionality as it solves my problem .因为这个 apk 具有解决我的问题的功能。 i cleared the errors of the source code which will comes when you import and after that i added the library to my project.我清除了导入时会出现的源代码错误,然后将库添加到我的项目中。 I used the PreferenceCompatFragment rather than PreferenceFragmentCompat, it solved my problem if anybody needs help it may help them also so that i am posting my solution to the above problem.我使用了 PreferenceCompatFragment 而不是 PreferenceFragmentCompat,它解决了我的问题,如果有人需要帮助,它也可以帮助他们,以便我发布我对上述问题的解决方案。 and i thank who are all helped me who and all given some valuable suggestion for the above problem.我感谢所有帮助我的人,他们为上述问题提供了一些宝贵的建议。 The below class below i have used instead of PreferenceFragmentCompat of v7 support library我使用下面的类代替了 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM