更改片段时,Android Fragment UI元素会消失吗?

时间:2016-12-12 03:54:14

标签: android android-fragments

我正在创建一个具有多个片段的Android应用程序,每个功能一个。我目前正在使用抽屉来访问每个功能,而在一个特定功能中,我使用的是FragmentPagerAdapterswitch between fragments within that fragment。当我创建第一个打开应用程序以访问我的片段时,我的layout.xml文件中定义的UI元素按预期加载。但是,当我使用抽屉切换到不同的片段并返回原始片段时,原始UI元素消失。

抽屉切换基本活动中的代码以访问不同的功能片段

public class BaseActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, ValueEventListener {
    FragmentManager fm;
    ArrayList<String> listOfAvailableRooms=new ArrayList<>();
    String timing="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        // start of own code
        fm = getSupportFragmentManager();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.base, menu);
        return true;
    }

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

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Fragment fragment;

        int id = item.getItemId();

        if (id == R.id.f_map) {
            fragment = new MapFragment();
        } else if (id == R.id.f_booking) {
            fragment = new CalendarFragment();
        } else if (id == R.id.f_roomSearch) {
            fragment = new RoomSearchFragment();
        } else if (id == R.id.f_authentication) {
            fragment = new AuthenticationFragment();
        } else if (id == R.id.nav_send) {
            fragment = new MapFragment().newInstance(3, new LatLng(-53.965623629921105, -5.974991060793399));
        } else {
            fragment = new MapFragment();
        }

        fm.beginTransaction().replace(R.id.main_container, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) return new MapFragment();
            return new MapFragment();
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Client";
                case 1:
                    return "Server";
            }
            return null;
        }
    }
}

功能的整体碎片

public class AuthenticationFragment extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    FragmentPagerAdapter adapterViewPager;

    private OnFragmentInteractionListener mListener;

    public AuthenticationFragment() {
        // Required empty public constructor
    }

    public static AuthenticationFragment newInstance(String param1, String param2) {
        AuthenticationFragment fragment = new AuthenticationFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_authentication, container, false);
        ViewPager vpPager = (ViewPager) view.findViewById(R.id.vpPager);
        adapterViewPager = new MyPagerAdapter(getFragmentManager());
        vpPager.setAdapter(adapterViewPager);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public static class MyPagerAdapter extends FragmentPagerAdapter {
        private static int NUM_ITEMS = 2;

        public MyPagerAdapter(FragmentManager fragmentManager){
            super(fragmentManager);
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position){
            switch (position){
                case 0: //CurrentBookings Fragment
                    return CurrentBookings.getInstance("Current");
                case 1: //UpcomingBookings Fragment
                    return UpcomingBookings.newInstance("Upcoming");
                default:
                    return null;
            }
        }

        // Returns page title for the top indicator
        @Override
        public CharSequence getPageTitle(int position){
            switch (position){
                case 0: //CurrentBookings Fragment
                    return "Current";
                case 1: //UpcomingBookings Fragment
                    return "Upcoming";
                default:
                    return null;
            }
        }
    }

}

包含消失的UI元素的片段

public class CurrentBookings extends Fragment {
    private Button myButton;

    // newInstance constructer for creating fragment with arguments
    public static CurrentBookings newInstance(String title){
        CurrentBookings currentBookings = new CurrentBookings();
        Bundle args = new Bundle();
        args.putString("title",title);
        currentBookings.setArguments(args);
        return currentBookings;
    }

    // Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        title = getArguments().getString("title");
    }

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

        myButton = (Button) view.findViewById(R.id.button1);
        return view;
    }
}

第一次打开片段时应用的屏幕截图 screenshot first open fragment

重新访问片段时应用的屏幕截图 enter image description here enter image description here

只有在手机方向更改时,才会再次显示UI元素。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

是,

您需要手动删除AuthenticationFragment的子片段。

当您设置适配器时,您必须在parentFragment中的arraylist中添加两个片段,这样您就可以获得片段的完整列表,以便您可以轻松删除父片段的onDestroyView()上的片段。

private class AuthenticationFragment extends Fragment{

private Arraylist fragmentList = new ArrayList<>();


private void setAdapter(){
    fragmentList.add(new FirstFragment());
    fragmentList.add(new SecondFragment());
............. code of adapter


}



    @Override
    public void onDestroyView() {
        super.onDestroyView();

        final FragmentManager fragmentManager = getFragmentManager();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        for (Fragment fragment : fragmentList) {
            fragmentTransaction.remove(fragment);
        }
        fragmentTransaction.commit();

    }

}

因为您在AuthenticationFragment中使用了FragmentPagerAdapter。