Сдвиг между фрагментами показывает одинаковую позицию 1-го фрагмента. - PullRequest
0 голосов
/ 23 мая 2018

Я боролся в течение нескольких дней по этому вопросу.Мой проект имеет 4 фрагмента, которые имеют одну и ту же плавающую кнопку.Мне удалось сослаться на фрагменты, чтобы позволить плавающей кнопке получить доступ к каждому, однако, хотя я переключаюсь между каждым фрагментом, он показывает положение только первого.вот мой код

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

    //set the drawer layout and navigation view
    mDrawerLayout = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            //set item selected persist highlight
            menuItem.setChecked(true);
            //close drawer
            mDrawerLayout.closeDrawers();
            //set action as per the item selected
            return true;
        }
    });

    //create an adapter that knows where each fragment is
    final LocationFragmentAdapter adapter = new LocationFragmentAdapter(this, getSupportFragmentManager());
    mViewPager = findViewById(R.id.viewPager);
    mViewPager.setAdapter(adapter);
    adapter.getItem(position);

    //set the function for the floating button to add a new item
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Log.i(LOG_TAG, "the current fragment " + adapter.getPageTitle(position));
            if(position == 0) {
                    Intent intent = new Intent(MainActivity.this, EditorActivity.class);
                    startActivity(intent);
                }
                else if (position == 1) {
                    Intent intent = new Intent(MainActivity.this, RecipeEditor.class);
                    startActivity(intent);
                }
        }
    });
}

это мой фрагмент Adapter

public class LocationFragmentAdapter extends FragmentPagerAdapter {

final int count = 4;
private int [] tabTitle = {R.string.inventory_platform, R.string.product_platform, R.string.customer_platform, R.string.order_platform};
private Context mContext;

public LocationFragmentAdapter(Context context, FragmentManager fm){
    super(fm);
    mContext = context;
}
@Override
public Fragment getItem(int position) {
    if(position == 0) {
        return new InventoryFragment();
    }else if(position == 1) {
        return new RecipeFragment();
    }else if(position == 2) {
        return new CustomerFragment();
    }else {
        return new OrderFragment();
    }

}

, это мой InventoryFragment

@Override
public void onActivityCreated(Bundle savedInstanceState){
    getActivity().getSupportLoaderManager().initLoader(STOCK_LOADER, null, this);
    super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
    final View rootView = inflater.inflate(R.layout.activity_main, container, false);
    //set empty activity
    ListView listView = rootView.findViewById(R.id.display_view);
    View emptyView = rootView.findViewById(R.id.empty_view);
    listView.setEmptyView(emptyView);
    //create a new cursor adapter
    mCursorAdapter = new PlatformCursorAdapter(getActivity(),null);
    listView.setAdapter(mCursorAdapter);
    //create onClick listener to inflate the editor view
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //create new intent to opend the editor
            Intent intent = new Intent(getActivity(), EditorActivity.class);
            //create Uri to pass the contents of the item selected to the edit view
            Uri currentItem = ContentUris.withAppendedId(StoreEntry.CONTENT_URI, id);
            intent.setData(currentItem);
            startActivity(intent);
        }
    });

    getLoaderManager().initLoader(STOCK_LOADER, null, this);

    return rootView;
}

и мой RecipeFragment

    }
@Override
public void onActivityCreated(Bundle savedInstanceState){
    getActivity().getSupportLoaderManager().initLoader(RECIPE_lOADER, null, this);
    super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
    final View rootView = inflater.inflate(R.layout.activity_main, container, false);
    //set empty activity
    ListView listView = rootView.findViewById(R.id.display_view);
    View emptyView = rootView.findViewById(R.id.empty_view);
    listView.setEmptyView(emptyView);
    //create a new cursor adapter
    mCursorAdapter = new RecipeCursorAdapter(getActivity(),null);
    listView.setAdapter(mCursorAdapter);
    //create onClick listener to inflate the editor view
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //create new intent to opened the editor
            Intent intent = new Intent(getActivity(), EditorActivity.class);
            //create Uri to pass the contents of the item selected to the edit view
            Uri currentItem = ContentUris.withAppendedId(RecipeEntry.CONTENT_URI, id);
            intent.setData(currentItem);
            startActivity(intent);
        }
    });


    return rootView;
}

Iеще не создали последние два фрагмента.Пожалуйста, дайте мне знать, если вы можете найти ошибку.

В журнале всегда отображается фрагмент инвентаря

1 Ответ

0 голосов
/ 23 мая 2018

Вам придется обновлять позицию каждый раз, когда страница выбирается с помощью прослушивателя пейджера

mPager.setOnPageChangeListener(new OnPageChangeListener() {


        @Override
        public void onPageScrollStateChanged(int arg0) { }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) { }

        @Override
        public void onPageSelected(int position) {
             this.position = position
        }

    });
...