Víctor Martín
Víctor Martín

Reputation: 3450

How to redirect to another page of a viewpager fragment?

I have a fragment activity with 2 classes, I have a button in one of this and I want when I click this button the viewpager change to the another class (tab/page).

How I can do that?

Thank you.

This is the code from one of the classes:

package com.victor.martin.agenda.app.fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.victor.martin.agenda.app.DB.DBManager;
import com.victor.martin.agenda.app.DB.Event;
import com.victor.martin.agenda.app.DatePickerFragment;
import com.victor.martin.agenda.app.R;
import com.victor.martin.agenda.app.TimePickerFragment;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by McFly on 11/05/2014.
 */
public class NewEventFragment extends Fragment implements TimePickerFragment.TimePickerFragmentListener,DatePickerFragment.DatePickerFragmentListener {

    int tmp_year, tmp_month, tmp_day, tmp_hour, tmp_minute;
    String tmp_description, tmp_location;

    Button bt_date, bt_time, bt_clear, bt_save;
    EditText et_description, et_location;
    Context _c;

    // Database Helper
    DBManager db;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_new_event, container, false);

        _c = getActivity();

        db = new DBManager(_c);

        bt_date = (Button)v.findViewById(R.id.bt_date);
        bt_time = (Button)v.findViewById(R.id.bt_time);
        bt_clear = (Button)v.findViewById(R.id.bt_clear);
        bt_save = (Button)v.findViewById(R.id.bt_save);
        et_description = (EditText)v.findViewById(R.id.et_description);
        et_location = (EditText)v.findViewById(R.id.et_location);

        bt_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog();
            }
        });

        bt_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog();
            }
        });

        bt_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bt_date.setText(getResources().getString(R.string.str_date));
                bt_time.setText(getResources().getString(R.string.str_time));
                et_description.setText(getResources().getString(R.string.str_empty));
                et_location.setText(getResources().getString(R.string.str_empty));
            }
        });

        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tmp_description = et_description.getText().toString();
                tmp_location = et_location.getText().toString();

                long timestamp = convertStringToTimestamp(tmp_year, tmp_month, tmp_day, tmp_hour, tmp_minute);
                Event tmp_event = new Event("HARDCODED_USER", timestamp, tmp_description, tmp_location);

                db.insertData(tmp_event);
                Log.i("SAVED", tmp_event.toString());
            }
        });

        return v;
    }

    public static NewEventFragment newInstance(String text) {

        NewEventFragment f = new NewEventFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }

    // Methods

    //Llamado cuando el usuario pulsa el botón de TimePicker
    public void showTimePickerDialog() {
        TimePickerFragment newFragment = new TimePickerFragment();
        newFragment.setTargetFragment(this, 0);
        newFragment.show(this.getFragmentManager(), "timePicker");
    }

    //Llamado cuando el usuario pulsa el botón de DatePicker
    public void showDatePickerDialog() {
        DatePickerFragment newFragment = new DatePickerFragment();
        newFragment.setTargetFragment(this, 0);
        newFragment.show(this.getFragmentManager(), "datePicker");
    }

    //Llamado cuando el usuario acaba la selección y los datos son enviados a la actividad
    @Override
    public void onFinishTimePickerDialog(int hourOfDay, int minute) {
        // TODO Auto-generated method stub
        //Toast.makeText(this, "Hora: " + hourOfDay + minute, Toast.LENGTH_SHORT).show();
        tmp_hour = hourOfDay;
        tmp_minute = minute;
        bt_time.setText(hourOfDay + ":" + minute);
    }

    //Llamado cuando el usuario acaba la selección y los datos son enviados a la actividad
    @Override
    public void onFinishDatePickerDialog(int year, int month, int day) {
        // TODO Auto-generated method stub
        //Toast.makeText(this, "Fecha: " + year + month + day, Toast.LENGTH_SHORT).show();
        tmp_year = year;
        tmp_month = month;
        tmp_day = day;
        bt_date.setText(day + "/" + month + "/" + year);
    }

    public long convertStringToTimestamp(int year, int month, int day, int hour, int minute){

        String converted_day = String.format("%02d", day);
        String converted_month = String.format("%02d", month);
        String converted_year = String.format("%02d", year);

        String converted_hour = String.format("%02d", hour);
        String converted_minute = String.format("%02d", minute);
        String converted_seconds = String.format("%02d", 0);

        String str_date= converted_day + "-" + converted_month + "-" + converted_year + " " + converted_hour + ":" + converted_minute + ":" + converted_seconds;
        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = null;
        try {
            date = (Date)formatter.parse(str_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date.getTime();

    }
}

Upvotes: 0

Views: 1434

Answers (1)

chartsai
chartsai

Reputation: 368

Use ViewPager instance in your activity, and call "ViewPager.setCurrentItem(your_fragment_position)" to change the current page(fragment) in pager.

For convenience reason, you can make a interface and extends it by Activity to help your fragment control the page.
For example:

Define a new interface:

public interface IViewPagerSwitcher {
  public void switchToPage(int newPagePositoin);
}

Make your activity extend the interface and implement it:

public class myActivity implements IViewPagerSwitcher {
  ...
  ViewPager mViewPager;
  ...
  @Override
  public void switchToPage(int newPagePositoin) {
    mViewPager.setCurrentItem(newPagePosition);
  }
  ...
}

Call the switch function in your Fragment:

...
IViewPagerSwitcher switcher = (IViewPagerSwitcher) getActivity();
switcher.switchToPage(your_new_page_position);
...

Upvotes: 2

Related Questions