Display current date in Viewpager manipulated layout

Asked

Viewed 270 times

0

When I click on a Main Activity button, a Viewpager is created that allows me to move between 7 layouts that I have. The pager is set to present first the layout called "domingo.xml" and everything works normally. I just want this layout to be shown a date, so 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 to test and the date code works and displays the date normally, but in the Domingo.xml layout (which is handled by Viewpager) I can’t at all.

This is the code of the button 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 Viewpager. Where should I write the date code? I have tried in several places, but it is always a mistake. I do not know if there is some conceptual error that I do not understand. I’m new to programming and this is the first time I’ve put on a forum. If you need more information tell me what I add. Thanks.

Code of the Pageradapter:

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;
}}

Code of Sunday.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 stayed 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 appeared, however, when I slide to the third layout hangs everything. What is happening ?

  • It is not enough to assign the String (of the formatted date) within the method getView of AdapterPages? It would be nice to just put the code of AdapterPages and its xml of View that it creates and adds to ViewPager.

  • @Wakim added the codes you requested...

  • Thank you Felipe, could you tell me where exactly you use the code that changes the textoData in relation to the ViewPager or was just for testing?

  • @Wakim I used for testing and also tried to write the whole date code directly on both Viewpager and Pageradapter. Where would be the correct ?

  • The most correct is in PagerAdapter. You need to add a logic within the getView that fills the TextView. And you don’t need a layout for each day (if the layout is similar), just one and add logic to customize depending on the position.

  • @Wakim They are similar, I understand what this logic would be, but I still don’t know how to make it. Could you give me an example of what this getView should look like ?

  • Yes, I will prepare an answer with this idea that I suggested.

  • @Wakim Ok, thank you very much. And don’t you notice, I just started.

  • Okay, I get it. Assuming you’re still using that switch, you can’t use fixed R.id.data_domingo, because it’s only Sunday.xml, in the case of the second.xml the id is another, right? For this you will have to create a variable called textViewId and set according to the switch value (equal to Resid). And use findViewById(textViewId) in the view and not in the container.

  • I think I get it, I’m gonna try and I’ll get back to you, thank you very much.

  • @Wakim excuse the delay, it worked perfectly, the emulator once in a while, but the device is perfect. I added an If for each case, like this: if (position == 1) { Textview textData = (Textview) Collection . findViewById(R.id.data_segunda); textData.setText(showData); } I believe it is not the right one, but it worked, thank you very much for your efforts in helping me. I don’t know if there’s a rule, but add yourself on the face. vlw, good night.

Show 6 more comments

1 answer

0


The ViewPager works in a similar way that the ListView, displaying a small part of the associated model.

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

In case your template is a list of dates, which can be derived from only one date.

I will assume that the domingo.xml will be the default for all dates, where what varies is the content of TextView whose ID is data_domingo that it displays. If there are more changes in the layout, just say that I help to mount.

Your Activity Pager remains the same.

What changes is yours AdapterPages which remains:

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 think it’s nice to also quote that the ViewPager builds the Views on demand, that is, it by default keeps in memory 3 Views (the visible, the previous and the next), as you navigate he destroys and builds the Views. This behavior can be changed by the attribute OffscreenPageLimit (being 1 by default), but his idea is to give fluidity to the movement of Slide.

References:

  1. https://stackoverflow.com/questions/2937086/how-to-get-the-first-day-of-the-current-week-and-month
  2. http://developer.android.com/reference/android/support/v4/view/ViewPager.html
  • I could not answer you with comment... I commented with reply (is above yours), I do not know if it is right, but I found no way out

  • Ok, you could have updated your question. If you can do that it is not to confuse who comes through your question;

  • Okay, and I delete the one I did wrong along with the comments ?

  • @Felipesantiago May be, but just migrate even. You can even put a marker, and put the most updated code so far.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.