Display current date in layout handled by ViewPager

0

When I click on a button in Main Activity, I create a ViewPager that allows me to navigate through the 7 layouts I have. The pager is set to display the layout called "Sunday.xml" first and everything works normally. I just want a date to be shown in this layout, for this I use this code:

    Locale local = new Locale("pt", "BR");
    DateFormat sdf = new SimpleDateFormat("EEEE - dd/MM", local);
    Date d = Calendar.getInstance().getTime();
    String mostrarData = sdf.format(d).toUpperCase(local);
    final TextView textoData = (TextView) findViewById(R.id.textView1);
    textoData.setText(mostrarData);

I created a new layout just for testing and the date code works and displays the date normally, but in the Sunday.xml layout (which is handled by the ViewPager) I can not do it at all.

This is the button code that calls the ViewPager:

public void btTela1(View v) {
startActivity(new Intent(getBaseContext(), Pager.class));
}

And this is the ViewPager code:

public class Pager extends Activity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pager);

    AdapterPages adapter = new AdapterPages();
    ViewPager myPager = (ViewPager) findViewById(R.id.pager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}}

There is also the PagerAdapter code used to configure the ViewPager. Where should I write the date code? I've tried it in several places, but it always makes mistakes. I also do not know if there are any conceptual errors that I do not understand. I'm new to programming and this is the first time I post in a forum. If I need more information tell me what I add. Thank you.

PagerAdapter code:

public class AdapterPages extends PagerAdapter {

@Override
public int getCount() {
    return 7;
}

@Override
public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
    case 0:
        resId = R.layout.domingo;
        break;
    case 1:
        resId = R.layout.segunda;
        break;
    case 2:
        resId = R.layout.terca;
        break;
    case 3:
        resId = R.layout.quarta;
        break;
    case 4:
        resId = R.layout.quinta;
        break;
    case 5:
        resId = R.layout.sexta;
        break;
    case 6:
        resId = R.layout.sabado;
        break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {

    return arg0 == ((View) arg1);
}

@Override
public Parcelable saveState() {
    return null;
}}

Sunday Code.xml:

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

    <TextView
        android:id="@+id/data_domingo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#BEBEBE"
        android:gravity="center"
        android:textStyle="bold" />
    ...

From what @Wakim taught me I modified a small part of the PagerAdapter code and it looked like this:

View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
Locale local = new Locale("pt", "BR");
DateFormat sdf = new SimpleDateFormat("EEEE - dd/MM", local);
Date d = Calendar.getInstance().getTime();
String mostrarData = sdf.format(d).toUpperCase(local);
TextView textoData = (TextView) collection
        .findViewById(R.id.data_domingo);
textoData.setText(mostrarData);
return view;

Now the date has appeared, however, when I slide to the third layout it locks everything. What's happening?

    
asked by anonymous 20.09.2014 / 22:16

1 answer

0

ViewPager works similarly to ListView , displaying a small part of the associated template.

The Model is associated with a Adapter , where it is responsible for returning the visual presentation of the model, for a given position.

In case your model is a list of dates, it can be derived from just one date.

I'll assume that domingo.xml will default to all dates, where what varies is the content of TextView whose ID is data_domingo that it displays. If there are more changes to the layout, just let me help.

Your Activity Pager remains the same.

What changes is your AdapterPages that stays:

public class AdapterPages extends PagerAdapter {

    // Data base do ViewPager (posição 0), onde cada posição derivará dessa
    Calendar mBaseDate = Calendar.getInstance();
    // DateFormat usado para formatar a data
    DateFormat mDateFormat = new SimpleDateFormat("EEEE - dd/MM", Locale.getDefault());

    // É legal "cachear" o LayoutInflater, para não ficar requisitando um toda hora. 
    LayoutInflater mLayoutInflater;

    public AdapterPages() {
        // Configurar a data base para corresponder ao primeiro dia da semana, domingo.
        mBaseDate.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
        mBaseDate.clear(Calendar.MINUTE);
        mBaseDate.clear(Calendar.SECOND);
        mBaseDate.clear(Calendar.MILLISECOND);

        // get start of this week in milliseconds
        mBaseDate.set(Calendar.DAY_OF_WEEK, mBaseDate.getFirstDayOfWeek());
    }

    @Override
    public int getCount() {
        // Ok, sao 7 dias
        return 7;
    }

    @Override
    public Object instantiateItem(View collection, int position) {

        if(mInflater == null) {
            mInflater = LayoutInflater.from(collection.getContext());
        }

        // Infla o layout padrão do ViewPager. É retornado uma
        // referência para a raiz (LinearLayout).
        // A partir dele, você consegue acessar todos os filhos.
        View view = mInflater.inflate(R.layout.domingo, null);

        TextView tv = view.findViewById(R.id.data_domingo);

        // Calculo qual o dia baseado na posicao e no dia base
        Calendar currentDate = (Calendar) mBaseDate.clone();
        currentDate.add(Calendar.DAY_OF_YEAR, posicao);

        // Fornece a data formatada relativa à posição do modelo
        tv.setText(mDateFormat.format(currentDate.getDate()).toUpperCase());

        // Voce pode fazer mais customizacoes aqui baseada na "view" e seus
        // elementos, e o seu modelo, a data relativa a posicao que vai ser exibida.

        ((ViewPager) collection).addView(view);

        return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }
}

I also like to quote that ViewPager builds Views on demand, that is, by default it keeps in memory 3 Views (visible, previous and next) as you navigate it destroys and builds Views . This behavior can be changed by the OffscreenPageLimit attribute (being 1 by default), but its idea is to give fluidity to the Slide movement.

References:

  • link
  • link
  • 21.09.2014 / 00:31