重新启动viewPager的Android片段

时间:2017-09-15 23:20:45

标签: android android-fragments android-viewpager

使用碎片时遇到的麻烦很少。 我有NavigationDrawer的活动。当我点击items navigationMenu中的ItemFragment时,系统会调用此对象。在ItemFragment内,我有一个TabLayoutViewPager有两个片段。

1. GoodsFragment
2. ServiceFragment

问题是当我调用itemfragment时,会在items片段中重新创建商品和服务片段。我尝试使用savedInstanceState(true),(false)并检查rootview for null和许多解决方案,但没有帮助我。每次创建片段时,都会创建另外两个片段。初学者尝试了许多方法,但无助。 这是我的代码。并提前致谢。

Item.java

public class Items extends Fragment {

    @Nullable

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fraglayout_items, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //you can set the title for your toolbar here for different fragments different titles
    getActivity().setTitle("Items");
    TabLayout tabLayout = (TabLayout)view.findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Goods"));
    tabLayout.addTab(tabLayout.newTab().setText("Services"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
    final PageAdapter adapter = new PageAdapter(getActivity().getFragmentManager(),tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }
        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }
        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
}
}

Service_Fragment.java

public class Service_fragment extends Fragment {
    public Service_fragment(){}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fraglayout_service, container, false);
    }@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        ItemDatabaseHandler db=new ItemDatabaseHandler(view.getContext());
        ListView sList=(ListView)view.findViewById(R.id.service_list);
        List<ItemDataModel> items = db.getAllServices();
        ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>();

        for (ItemDataModel item : items) {
            Map<String, String> datum = new HashMap<String, String>(2);
            datum.put("name", item.getName());
            datum.put("price", "\u20B9"+item.getPrice());
            datum.put("available", ""+item.getS_final());
            data.add(datum);
        }

        SimpleAdapter adapter = new SimpleAdapter(view.getContext(), data, R.layout.item_row, new String[] {"name", "price","available"}, new int[] {R.id.item_name, R.id.item_price,R.id.item_available});
        sList.setAdapter(adapter);
    }
}

Goods_fragment.java也会保存为类名更改的服务。 还尝试在onDetach中销毁项目片段,但没有运气。

MainActivity.java

package co.mastersindia.autotax;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    public final static int REQUEST_CODE = 10101;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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);
        displaySelectedScreen(R.id.nav_createinvoice);

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


    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        displaySelectedScreen(item.getItemId());
        return true;
    }
    private void displaySelectedScreen(int itemId) {

        //creating fragment object
        Fragment fragment = null;

        //initializing the fragment object which is selected
        switch (itemId) {
            case R.id.nav_createinvoice:
                fragment = new CreateInvoice();
                break;
            case R.id.nav_viewinvoice:
                fragment = new ViewInvoice();
                break;
            case R.id.nav_tax:
                fragment = new Tax();
                break;
            case R.id.nav_items:
                fragment = new Items();
                break;
            case R.id.nav_busmgmt:
                fragment = new BusinessManagement();
                break;
            case R.id.nav_settings:
                Intent i=new Intent(MainActivity.this,SettingsActivity.class);
                startActivity(i);
                break;
            case R.id.nav_customers:
                fragment = new Customer();
                break;
            case R.id.nav_suppliers:
                fragment = new Suppliers();
                break;
            case R.id.nav_cat:
                fragment = new Categories();
                break;
        }

        //replacing the fragment
        if (fragment != null) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.content_frame, fragment);
            transaction.commit();
        }

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

2 个答案:

答案 0 :(得分:0)

在适配器中,每次移动到某个位置时,都会重新创建片段。检查上面的示例代码

初始化您的视图寻呼机

        viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

在setupViewPager中添加片段的内容

    private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), "ONE");
    adapter.addFrag(new TwoFragment(), "TWO");
    adapter.addFrag(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
}

然后在你的片段中,当你移动到那个位置时,只需从数组中获取存储的片段,就像上面的示例适配器一样

    class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

<强>更新

当您创建每个片段时,必须为每个片段添加唯一ID,以便能够检查它是否已存在。请查看以下示例

 FragmentManager fManager = getFragmentManager();
 FragmentTransaction fTransaction = fManager.beginTransaction();
 Fragment fragment = fManager.findFragmentByTag("uniqueTag");
 if (fragment == null) {
     fTransaction.add(R.id.fragment_list, new ListFrag(), "uniqueTag");
     else { // re-use the old fragment
     fTransaction.replace(R.id.fragment_list, fragment, "uniqueTag");

答案 1 :(得分:0)

对于面临此问题的任何人,请执行以下操作: 使用var arr1 = ['Mar19','Apr18','Jun18','Jul18','May18','Jan19']; var arr2 =['55','2','3','0','21','132']; function datesort(arr){ return arr.concat().sort((a,b)=>{ a = a.replace(/(\d+)(.*)/g,' 1 $1'); // Month 1 YEAR b = b.replace(/(\d+)(.*)/g,' 1 $1'); // Month 1 YEAR return new Date(a) - new Date(b) }) } var after_arr1 =new datesort(arr1); var after_arr2 = arr1.reduce(function(a,b,c){ var ind = after_arr1.indexOf(b); a[ind] = arr2[c] return a },[]); console.log(after_arr1.join(',')); console.log(after_arr2.join(','))代替getChildFragmentManager()

getSupportFragmentManager()

希望这会有所帮助