Переключение между фрагментами из счетчика на панели инструментов с помощью активности просмотра

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

вот мой код

public class Main2Activity extends AppCompatActivity {

    Spinner gotoAyat;
    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;
    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    private static int id = 0;
    Intent intent;

    ViewPager vp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        intent = getIntent();

        id = intent.getIntExtra("idvalueShould1",0);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        gotoAyat = (Spinner) findViewById(R.id.gotoSpinner);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        String[] str = new String[] {"[Ayat No.]","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"
                ,"20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38",
                "39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58"
                ,"59","60","61","62","63","64","65","66","67","68","69","70","71","72","73","74","75","76","77"
                ,"78","79","80","81","82","83"};

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        final RelativeLayout cn = findViewById(R.id.constraintLayout);

        ArrayAdapter<String> arradp = new ArrayAdapter<String>(Main2Activity.this,
                R.layout.spinnerstyle,
                str
                );
        enter code herearradp.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        gotoAyat.setPrompt("Ayat No.");
        gotoAyat.setAdapter(arradp);
        mViewPager.setRotationY(180);
        cn.setRotationY(180);
       gotoAyat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
           @Override
           public void onItemSelected(AdapterView<?> parent, View view, int position, long idparamaeter) {
               if(!gotoAyat.getSelectedItem().toString().equals("[Ayat No.]"))
               {
                   id = Integer.parseInt(gotoAyat.getSelectedItem().toString()) - 1;
                   FragmentManager fragmentManager = getSupportFragmentManager();
//                   FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                   int idin = Integer.parseInt(gotoAyat.getSelectedItem().toString()) - 1;
                   switch(position){
                               Bundle args = new Bundle();
                           args.putInt("Id", idin);
                           args.putInt("language", settings.defaultLanguage);
                           fragment_ayat2 fragment = new fragment_ayat2();
                           fragment.setArguments(args);
                           id++;

//                           //getSupportFragmentManager().beginTransaction()
  //                                 .replace(R.id.constraintLayout, //fragment).commit();
    //               }
  //                 FragmentManager fragmentManager = //getSupportFragmentManager();
////                   fragment_ayat2 fragmentt = new fragment_ayat2();
////
////                   FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
////                   fragmentTransaction.commit();
               }
               }
           @Override
           public void onNothingSelected(AdapterView<?> parent) {
           }
       });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main2, 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();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {

                    Intent intent = new Intent(this, settings.class);
                    //      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        settings language = new settings();
        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            switch(position){
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 13:
                case 14:
                case 15:
                case 16:
                case 17:
                case 18:
                case 19:
                case 20:
                case 21:
                case 22:
                case 23:
                case 24:
                case 25:
                case 26:
                case 27:
                case 28:
                case 29:
                case 30:
                case 31:
                case 32:
                case 33:
                case 34:
                case 35:
                case 36:
                case 37:
                case 38:
                case 39:
                case 40:
                case 41:
                case 42:
                case 43:
                case 44:
                case 45:
                case 46:
                case 47:
                case 48:
                case 49:
                case 50:
                case 51:
                case 52:
                case 53:
                case 54:
                case 55:
                case 56:
                case 57:
                case 58:
                case 59:
                case 60:
                case 61:
                case 62:
                case 63:
                case 64:
                case 65:
                case 66:
                case 67:
                case 68:
                case 69:
                case 70:
                case 71:
                case 72:
                case 73:
                case 74:
                case 75:
                case 76:
                case 77:
                case 78:
                case 79:
                case 80:
                case 81:
                case 82:
                    Bundle args = new Bundle();
                    args.putInt("Id", id);
                    args.putInt("language", settings.defaultLanguage);
                    fragment_ayat2 fragment = new fragment_ayat2();
                    fragment.setArguments(args);
                    id++;

                    return fragment;
                    default:
                        return null;
            }
        }
        @Override
        public int getCount() {
            return 83;
        }
    }
}

вот мой основной xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fitsSystemWindows="true"
    tools:context="bukhari.example.com.surayaseen.Main2Activity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

            <!--<Spinner-->
                <!--android:layout_width="wrap_content"-->
                <!--android:layout_height="wrap_content"-->
                <!--android:id="@+id/gotoSpinner"-->
                <!--android:layout_marginTop="10dp"-->
                <!--android:foregroundGravity="right"-->
                <!--android:layout_marginEnd="2dp"-->
                <!--android:layout_marginRight="2dp"-->
                <!--android:layout_marginLeft="40dp"-->
                <!--android:layout_marginStart="40dp"-->
                <!--app:popupTheme="@style/Base.Theme.AppCompat.Light"-->
                <!--&gt;-->
            <!--</Spinner>-->

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:rotationY="180"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</LinearLayout>

У меня есть один фрагмент, и я изменяю данные динамически, как показано в коде. Я передаю "id" фрагменту, на основании которого данные будут отображаться во фрагменте. но из-за поведения по умолчанию в режиме просмотра пейджера, при котором просмотр пейджера загружается хотя бы на одну следующую страницу, когда я выбрал что-то из прядильщика, он не отображается в то время, но после выбора, когда я проведу пальцем по следующему и снова, будет показан следующий выбранный фрагмент из прядильщика.

0 ответов

Другие вопросы по тегам