片段滑动时没有重新创建和重叠

时间:2019-02-04 22:31:46

标签: java android android-fragments

我看到了很多类似的问题,甚至还回答了一个问题(隐藏/显示),但是我发现,当您轮换设计或开启夜间模式(嵌入Google体验)时,此时打开的片段将被替换其他片段的背景。我该如何解决?如果我们将view替换为另一个片段<fragment>,似乎出现了,但是我不确定。同样在API中,我读到有一种setRetainInstance方法可以在旋转片段时保存该片段,但是将其添加到onCreateView并没有任何改变。

/// activity_main

<!-- Fragments Container -->

<include
    android:id="@+id/fragment"
    layout="@layout/activity_main2"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/navigation"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<!-- Bottom Navigation View -->

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="0dp"
    android:layout_marginEnd="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:menu="@menu/bottom_navigation" />

/// MainActivity

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {

    final Fragment fragment1 = new MapsFragment();
    final Fragment fragment2 = new StatsFragment();
    final Fragment fragment3 = new NewsFragment();
    final Fragment fragment4 = new MoreFragment();
    final FragmentManager fm = getSupportFragmentManager();
    private int tabId;
    Fragment active = fragment1;

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

        loadData();
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navigation.setSelectedItemId(tabId);

        switch (tabId){
            case R.id.navigation_map:
                fm.beginTransaction().add(R.id.fragment, fragment4, "4").hide(fragment4).commit();
                fm.beginTransaction().add(R.id.fragment, fragment3, "3").hide(fragment3).commit();
                fm.beginTransaction().add(R.id.fragment, fragment2, "2").hide(fragment2).commit();

                fm.beginTransaction().add(R.id.fragment,fragment1, "1").commit();
                return;
            case R.id.navigation_stats:
                fm.beginTransaction().add(R.id.fragment, fragment4, "4").hide(fragment4).commit();
                fm.beginTransaction().add(R.id.fragment, fragment2, "2").hide(fragment2).commit();
                fm.beginTransaction().add(R.id.fragment, fragment1, "1").hide(fragment1).commit();

                fm.beginTransaction().add(R.id.fragment,fragment3, "3").commit();
                return;
            case R.id.navigation_news:
                fm.beginTransaction().add(R.id.fragment, fragment4, "4").hide(fragment4).commit();
                fm.beginTransaction().add(R.id.fragment, fragment3, "3").hide(fragment3).commit();
                fm.beginTransaction().add(R.id.fragment, fragment1, "1").hide(fragment1).commit();

                fm.beginTransaction().add(R.id.fragment,fragment2, "2").commit();
                return;
            case R.id.navigation_more:
                fm.beginTransaction().add(R.id.fragment, fragment3, "3").hide(fragment3).commit();
                fm.beginTransaction().add(R.id.fragment, fragment2, "2").hide(fragment2).commit();
                fm.beginTransaction().add(R.id.fragment, fragment1, "1").hide(fragment1).commit();

                fm.beginTransaction().add(R.id.fragment,fragment4, "4").commit();
                return;
                default:
                    fm.beginTransaction().add(R.id.fragment, fragment4, "4").hide(fragment4).commit();
                    fm.beginTransaction().add(R.id.fragment, fragment3, "3").hide(fragment3).commit();
                    fm.beginTransaction().add(R.id.fragment, fragment2, "2").hide(fragment2).commit();
                    fm.beginTransaction().add(R.id.fragment,fragment1, "1").commit();
        }
    }
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            tabId = item.getItemId();
            //Fragment selectedFragment = null;
            switch (tabId) {
                case R.id.navigation_map:
                    fm.beginTransaction().hide(active).show(fragment1).commit();
                    active = fragment1;
                    return true;
                case R.id.navigation_stats:
                    fm.beginTransaction().hide(active).show(fragment2).commit();
                    active = fragment2;
                    return true;
                case R.id.navigation_news:
                    fm.beginTransaction().hide(active).show(fragment3).commit();
                    active = fragment3;
                    return true;
                case R.id.navigation_more:
                    fm.beginTransaction().hide(active).show(fragment4).commit();
                    active = fragment4;
                    return true;
            }
            return false;
        }
    };

    @SuppressLint("ApplySharedPref")
    private void saveData(){
        SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("tabId", tabId).commit();
    }

    private void loadData(){
        SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
        tabId = preferences.getInt("tabId",0);
    }

    @Override
    protected void onStop() {
        saveData();
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tabId",tabId);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

overlapping

2 个答案:

答案 0 :(得分:0)

尝试一下:

findViewById<BottomNavigationView>(R.id.bottom_navigation)
                .setOnNavigationItemSelectedListener(object : BottomNavigationView.OnNavigationItemSelectedListener {
                    override fun onNavigationItemSelected(item: MenuItem): Boolean {
                        var fragment : Fragment = CategoriesFragmentKT.newInstance()
                        when (item.itemId) {
                            R.id.action_categories -> fragment= CategoriesFragmentKT.newInstance()
                            R.id.action_search -> fragment = SearchFragment.newInstance()
                            R.id.action_favorites -> fragment = FavoritesFragment.newInstance()
                        }
                        fragmentExecutor(fragment, R.id.container, false)
                        return true
                    }
                })

        fragmentExecutor(CategoriesFragmentKT.newInstance(), R.id.container, false)

而不是添加片段,而是重新放置它们:

 fun fragmentExecutor(fragment: Fragment?, containerId: Int, push: Boolean) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()

        fragmentTransaction.replace(containerId, fragment)

        if (push && fragment != null) {
            fragmentTransaction.addToBackStack(fragment.tag)
        }
        fragmentTransaction.commitAllowingStateLoss()
    }

答案 1 :(得分:0)

找到了解决方案。在旋转之前,android根据生命周期活动调用onDestroy(),而在同一活动中保存所有活动视图的状态,因此,您具有已安装片段的片段容器的状态。 因此,要除去重叠部分,将活动片段隐藏在onDestroy()中就足够了。确保提交commitAllowingStateLoss()而不是commit(),否则将产生错误。  我的代码:

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity {

    final Fragment mapsFragment = new MapsFragment();
    final Fragment statsFragment = new StatsFragment();
    final Fragment newsFragment = new NewsFragment();
    final Fragment moreFragment = new MoreFragment();
    final FragmentManager fm = getSupportFragmentManager();

    Fragment firstFragment;
    private int tabId;

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

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);

        loadData();
        setOnCreateFragment(navigation,tabId);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            tabId = item.getItemId();
            switch (tabId) {
                case R.id.navigation_map:
                    fm.beginTransaction().hide(firstFragment).show(mapsFragment).commit();
                    firstFragment = mapsFragment;
                    break;
                case R.id.navigation_stats:
                    fm.beginTransaction().hide(firstFragment).show(statsFragment).commit();
                    firstFragment = statsFragment;
                    break;
                case R.id.navigation_news:
                    fm.beginTransaction().hide(firstFragment).show(newsFragment).commit();
                    firstFragment = newsFragment;
                    break;
                case R.id.navigation_more:
                    fm.beginTransaction().hide(firstFragment).show(moreFragment).commit();
                    firstFragment = moreFragment;
                    break;
            }
            return true;
        }
    };

    private void setOnCreateFragment(BottomNavigationView navigation, int tabId){

        fm.beginTransaction().add(R.id.container, moreFragment, "4").hide(moreFragment).commit();
        fm.beginTransaction().add(R.id.container, newsFragment, "3").hide(newsFragment).commit();
        fm.beginTransaction().add(R.id.container, statsFragment, "2").hide(statsFragment).commit();
        fm.beginTransaction().add(R.id.container, mapsFragment, "1").hide(mapsFragment).commit();

        if(tabId != -1){
            switch (tabId){
                case R.id.navigation_map:
                    fm.beginTransaction().show(mapsFragment).commit();
                    firstFragment = mapsFragment;
                    break;
                case R.id.navigation_stats:
                    fm.beginTransaction().show(statsFragment).commit();
                    firstFragment = statsFragment;
                    break;
                case R.id.navigation_news:
                    fm.beginTransaction().show(newsFragment).commit();
                    firstFragment = newsFragment;
                    break;
                case R.id.navigation_more:
                    fm.beginTransaction().show(moreFragment).commit();
                    firstFragment = moreFragment;
                    break;
            }
            navigation.setSelectedItemId(tabId);
        } else  {
            fm.beginTransaction().show(mapsFragment).commit();
            firstFragment = mapsFragment;
        }

    }

    @SuppressLint("ApplySharedPref")
    private void saveData(){
        SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("tabId", tabId).commit();
    }

    private void loadData(){
        SharedPreferences preferences = getSharedPreferences("preferences",MODE_PRIVATE);
        tabId = preferences.getInt("tabId",-1);
        //tag   = preferences.getString("tag",null);
    }

    @Override
    protected void onStop() {
        saveData();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        fm.beginTransaction().hide(firstFragment).commitAllowingStateLoss();
        super.onDestroy();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}