Get ViewPager index displayed on Android screen

2

I have a ViewPager located at the bottom of my app, and I'm trying to get its index, id or any reference to the ViewPager that is displayed on the screen so that depending on which is displayed, the button they share makes an action u another in the onClick () method. A basic idea of what he raised is:

    //Funcion de escucha del Button
    Button btnTick = (Button) rootView.findViewById(R.id.buttonInvertirTick);
    btnTick.setOnClickListener(new View.OnClickListener() {
        public void onClick (View v) {
             if(index1.isShowed()==true){
               //Tareas a realizar
             } else (index2.isShowed()==true){
               //Tareas a realizar
             }
        }
    });

Deputy code

fragment_screen_slide_page.xml:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <LinearLayout
        android:id="@+id/LayoutEditText"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvIndex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textIsSelectable="false"
            android:layout_marginTop="11dp"
            android:layout_marginLeft="7dp"
            android:textSize="25dp" />

        <EditText
            android:id="@+id/valores"
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:inputType="phone" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/LayoutEditText"
        android:orientation="horizontal">

        <Button
            android:id="@+id/buttonInvertirTick"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:background="@drawable/success"/>

    </LinearLayout>

</LinearLayout>

</LinearLayout>

ScreenSlidePageFragment.java:

public class ScreenSlidePageFragment extends Fragment {

/**
 * Key to insert the background color into the mapping of a Bundle.
 */
private static final String BACKGROUND_COLOR = "color";

/**
 * Key to insert the index page into the mapping of a Bundle.
 */
private static final String INDEX = "index";

/**
 * Key to insert the text into the mapping of a Bundle.
 */
private static final String TEXTO = "index";

private int color;
private int index;
private String textoSta;

/**
 * Instancia un nuevo fragment con un background color, el indice de la pagina y un texto
 *
 * @param color background color
 * @param index index page
 * @param texto texto de tipo de cotizacion
 * @return a new page
 */
public static ScreenSlidePageFragment newInstance(int color, int index, String texto) {

    // Instantiate a new fragment
    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();

    // Save the parameters
    Bundle bundle = new Bundle();
    bundle.putInt(BACKGROUND_COLOR, color);
    bundle.putInt(INDEX, index);
    bundle.putString(TEXTO, texto);
    fragment.setArguments(bundle);
    fragment.setRetainInstance(true);

    return fragment;

}

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    // Carga los parametros con los que se sobrecargo cuando la precarga inicial del fragment se completa
    this.color = (getArguments() != null) ? getArguments().getInt(
            BACKGROUND_COLOR) : Color.DKGRAY;

    this.textoSta = (getArguments() != null) ? getArguments().getString(TEXTO)
            : "";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.fragment_screen_slide_page, container, false);

    // Establece el texto del TextView con el que se sobrecargo
    TextView tvIndex = (TextView) rootView.findViewById(R.id.tvIndex);
    tvIndex.setText(textoSta);

    // Establece el color de fondo con el que se sobrecargo
    rootView.setBackgroundColor(color);

    //Funcion de escucha del Button
    Button btnTick = (Button) rootView.findViewById(R.id.buttonInvertirTick);
    btnTick.setOnClickListener(new View.OnClickListener() {
        public void onClick (View v) {
            Context context = getActivity();
            CharSequence text = "Hello toast!";
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    });




    return rootView;

}
}

The way in which I installed the ViewPager in the classes:

        // Instantiate a ViewPager
    pager = (ViewPager) this.findViewById(R.id.viewPager);

    // Create an adapter with the fragments we show on the ViewPager
    MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(
            getSupportFragmentManager());
    adapter.addFragment(ScreenSlidePageFragment.newInstance(getResources()
            .getColor(R.color.backgroundPager), 0, "Saldo a invertir: "));
    adapter.addFragment(ScreenSlidePageFragment.newInstance(getResources()
            .getColor(R.color.backgroundPager), 1, "Valores a comprar: "));
    pager.setAdapter(adapter);

I hope your help!

    
asked by Eduardo 25.05.2017 в 10:20
source

2 answers

2

From the API 22 you can use the getCurrentItem () method

a> of ViewPager .

int index = pager.getCurrentItem();

But you can also get it by using SimpleOnPageChangeListener . Create this class that is a listener to detect the selected page in ViewPager :

public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {

    private int currentPage;

    @Override
    public void onPageSelected(int position) {
        currentPage = position;  //*** Aquí se obtiene el indice!
    }

    public final int getCurrentPage() {
        return currentPage;
    }
}

and assign it to your ViewPager :

 // Instantiate a ViewPager
pager = (ViewPager) this.findViewById(R.id.viewPager);
pager.setOnPageChangeListener(new DetailOnPageChangeListener());

or assign the listener directly:

     // Instantiate a ViewPager
pager = (ViewPager) this.findViewById(R.id.viewPager);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

       private int currentPage;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
             currentPage = position;  //*** Aquí se obtiene el indice!
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }

        public final int getCurrentPage() {
           return currentPage;
        }

    });
    
answered by 25.05.2017 / 19:20
source
2

Create a listener and put it in your ViewPager :

/**
         * Obtener la posicion actual del ViewPager mediante
         * extendiendo SimpleOnPageChangeListener class y añadiendolo a tu método
         */
        public class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {

            private int currentPage;

            @Override
            public void onPageSelected(int position) {
                currentPage = position;
            }

            public final int getCurrentPage() {
                return currentPage;
            }
        }

According to the method you mention, in your case it would be like this, similar to the method I mention, but this is not how it works or if it could work:

pageListener = new PageListener();
pager.setOnPageChangeListener(pageListener);

private int currentPage;

    private static class PageListener extends SimpleOnPageChangeListener{
            public void onPageSelected(int position) {
                Log.i(TAG, "página seleccionado " + position);
                   currentPage = position;
        }
    }
    
answered by 25.05.2017 в 10:30