我正在尝试使用一个包含导航视图的独特活动,其选项将打开另一个片段。一切正常,除非从另一个片段(从导航视图中打开)返回时重新创建MainFragment。我想知道如何避免这种情况,因为它再次加载了列表。

主要活动:

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(R.string.home);
        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.addDrawerListener(toggle);
        toggle.syncState();

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

        getSupportFragmentManager().beginTransaction()
            .add(R.id.layout, new MainFragment())
            .commit();
   }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
                navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
                getSupportFragmentManager().popBackStack();
            } else {
                super.onBackPressed();
            }
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        }

        switch (item.getItemId()) {
            case R.id.nav_history:
                getSupportFragmentManager().beginTransaction()
                    .replace(R.id.layout, new Fragment2())
                    .addToBackStack(null)
                    .commit();
                break;
            case R.id.nav_settings:
                break;
            case R.id.nav_logout:
                break;
        }

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


主要片段:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import br.com.example.adapters.ScheduledServicesAdapter;
import br.com.example.entities.ScheduledService;

public class MainFragment extends Fragment {


    private final class ScheduleServiceTask extends AsyncTask<Void, Void, List<ScheduledService>> {

        @Override
        protected List<ScheduledService> doInBackground(Void... params) {
            mList = new ArrayList<>();
            mList.add(new ScheduledService(new Date(), 250.50, 0));
            mList.add(new ScheduledService(new Date(), 50.75, 0));

            return mList;
        }

        @Override
        protected void onPostExecute(List<ScheduledService> scheduledServices) {
            super.onPostExecute(scheduledServices);
            setData(scheduledServices);
        }
    }

    private RecyclerView mRecyclerView;
    private ScheduledServicesAdapter mAdapter;
    private List<ScheduledService> mList;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        super.onCreateView(inflater, parent, savedInstanceState);
        return inflater.inflate(R.layout.content_main, parent, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(),
            linearLayoutManager.getOrientation());

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(dividerItemDecoration);

        new ScheduleServiceTask().execute();
    }

    private void setData(List<ScheduledService> list) {
        ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_bar);
        progressBar.setVisibility(View.GONE);

        if (!list.isEmpty()) {
            mAdapter = new ScheduledServicesAdapter(list);
            mRecyclerView.setAdapter(mAdapter);
        } else {
            TextView emptyText = (TextView) getActivity().findViewById(R.id.empty_text);
            emptyText.setVisibility(View.VISIBLE);
        }
    }
}


片段2具有用于测试目的的hello world文本视图。

最佳答案

当您将MainFragment放入BackStack时(表示该视图
fragmentvisible不是Fragment2,因为onCreateView
屏幕),则属于该视图的所有视图都将被销毁。
然后,当您从另一个片段返回MainFragment时,
MainFragment将被重新创建。这意味着onViewCreatednew ScheduleServiceTask().execute();将是
再次打电话。
对于您的情况,我建议:


onCreate移到requestGetData()
另一种方法(例如:mAdapter
初始化adapter并将mRecyclerView设置为onViewCreated()
setData()方法上,您所需要做的就是为mAdapter重置数据并调用notifyDatasetChanged()函数。

关于android - Android-如何避免按下后退按钮时重新创建 fragment ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43600793/

10-11 15:07