I’m having this problem. I created an activity with two Buttons and a TextView. The TextView is changed by pressing the Button “Next” and the Button “Previous” is used to change the TextView back to its original (which is textview1). But when “Previous” is pressed while textview1 is displayed or when “Next” is pressed while textview2 is displayed, the application gets an error and is shut down as a consequence. What I want to achieve now is to make the Button “Previous” disappear when textview1 is on and the Button “Next” when textview2 is on.
This is class I currently use:
package com.example.test8;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
public class Main extends Activity {
private static final String[] Texts=
{"textview1",
"textview2"
};
int textIdx = 0;
TextView Text;
ImageButton Next;
ImageButton Previous;
public static String getText(int idx) {
return Texts[idx];
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView) findViewById(R.id.text);
ImageButton Next = (ImageButton) findViewById(R.id.Next);
ImageButton Previous = (ImageButton) findViewById(R.id.Previous);
Text.setText(getText(textIdx));
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textIdx++;
Text.setText(getText(textIdx));
}
});
Previous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textIdx--;
Text.setText(getText(textIdx));
}
});
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
I thought about using an else if statement, but I couldn’t make it work, because I lack the knowledge and experience. If someone could help me out here, that would be great. Thanks in advance.
You should disable the buttons to prevent a user from clicking it when there is nothing ahead or behind it in your array.