-2

I am developing a quotes app that has next/previous, and copy buttons.

this is the code :

    Button btn1;
     String countires[];
     int i=0;
        /** Called when the activity is first created. */
     @Override
      public void onCreate(Bundle savedInstanceState)
     {
     super.onCreate(savedInstanceState);
         setContentView(R.layout.prob2);

btn1 = (Button) findViewById(R.id.prob2_btn1);

countires = getResources().getStringArray(R.array.country);

for (String string : countires)
{
    Log.i("--: VALUE :--","string = "+string);
}

btn1.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View arg0)
    {
        // TODO Auto-generated method stub
        String  country  = countires[i];
        btn1.setText(country);
        i++;
        if(i==countires.length)
            i=0;
    }
});
}

I need the onClick code for "previous" button to show previous string in textView ???

Swayam
  • 16,294
  • 14
  • 64
  • 102
A.J
  • 726
  • 1
  • 7
  • 19

2 Answers2

4

create a new member for your Activity like:

int actual = 0;

Then create a 'next' button:

nextButton = (Button) findViewById(...);

nextButton.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View arg0)
    {
        actual = actual < countires.length - 1 ? actual + 1 : actual;
        String  country  = countires[actual];
        btn1.setText(country);
    }
});

Same goes for the previous button:

prevButton = (Button) findViewById(...);

prevButton.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View arg0)
    {
        actual = actual > 0 ? actual - 1 : actual;
        String  country  = countires[actual];
        btn1.setText(country);
    }
});
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
2

That would be:

// Prev
if ( i > 0 ) {
    i--;
} else {
    i = countires.length - 1;
}
String  country  = countires[i];
btn1.setText(country);

Edit: most sense would be to change the next button as well. Because in the next method, you're now increasing i after you set the text. That's messing up the logic quite a bit.

// Next
if ( i < countires.length - 1 ) {
    i++;
} else {
    i = 0;
}
String  country  = countires[i];
btn1.setText(country);
Jochem
  • 2,995
  • 16
  • 18