I am trying to make a two player tic-tac-toe game. When the first player clicks the OnClick method with mark X on the button, but I stuck - I don't know how to make the onClick() to detect when the 2nd player clicked and how to mark O on the button ..plz help.. My .java is below
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBoard();
}
int c[][];
int i, j, k = 0;
Button b[][];
TextView textView;
private void setBoard() {
b = new Button[4][4];
c = new int[4][4];
// Button = (TextView) findViewById(R.id.newgame);
b[1][3] = (Button) findViewById(R.id.one);
b[1][2] = (Button) findViewById(R.id.two);
b[1][1] = (Button) findViewById(R.id.three);
b[2][3] = (Button) findViewById(R.id.four);
b[2][2] = (Button) findViewById(R.id.five);
b[2][1] = (Button) findViewById(R.id.six);
b[3][3] = (Button) findViewById(R.id.seven);
b[3][2] = (Button) findViewById(R.id.eight);
b[3][1] = (Button) findViewById(R.id.nine);
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++)
c[i][j] = 2;
}
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
b[i][j].setOnClickListener(new MyClickListener(i, j));
if (!b[i][j].isEnabled()) {
b[i][j].setText("o");
b[i][j].setEnabled(true);
}
}
}
}
class MyClickListener implements View.OnClickListener {
int x;
int y;
public MyClickListener(int x, int y) {
this.x = x;
this.y = y;
}
public void onClick(View view) {
if (b[x][y].isEnabled()) {
b[x][y].setEnabled(false);
b[x][y].setText("X");
c[x][y] = 0;
textView.setText("");
//WHAT NEXT
}
}
}
}
}
Simply use a boolean to detetct the click. Say a boolean isFirstPlayerTurn is true when button is clicked first time. Make it false for second turn. Do this for all turns and you will know which player is clicking the button.
Example:
private boolean isFirstPlayerTurn = true;
...
void onclick() {
if (isFirstPlayerTurn) {
// clicked by player 1
isFirstPlayerTurn = false;
} else {
// clicked by player 2
isFirstPlayerTurn = true;
}
}
You should probably add a new variable
int playerTurn;
which should initially be set to 1. On the first onClick() execution, the value of playerTurn is 1, so place an X, and change the playerTurn to 2. On the second click, when you check the value of playerTurn, you will place an O, and change its value to 1. And this keep on going.
int player = 1;
public void onClick(View view){
if (b[x][y].isEnabled() {
b[x][y].setEnabled(false);
if (player == 1){
b[x][y].setText("X");
c[x][y] = 0;
player = 1;
} else {
b[x][y].setText("O");
c[x][y] = 1;
player = 2;
}
}
}
Related
I am newbie on Android Studio. I have a question.
I am making a match cards application.
After a failed match cards flipping back after 0,5 sec. But while this time, you can still check other cards. I want to disable that. I'm extends Button to a class. I'm posting both of this scripts. Thanks for your helps.
This is my Card Class.
public class kart extends Button {
boolean acikMi = false;
boolean cevrilebilir = true;
int arkaPlanID;
int onPlanID=0;
Drawable on;
Drawable d;
public kart(Context context, int id) {
super(context);
setId(id);
arkaPlanID = R.drawable.arka1;
if(id%8==1)
onPlanID = R.drawable.c1;
if(id%8==2)
onPlanID = R.drawable.c2;
if(id%8==3)
onPlanID = R.drawable.c3;
if(id%8==4)
onPlanID = R.drawable.c4;
if(id%8==5)
onPlanID = R.drawable.c5;
if(id%8==6)
onPlanID = R.drawable.c6;
if(id%8==7)
onPlanID = R.drawable.c7;
if(id%8==0)
onPlanID = R.drawable.c8;
d = AppCompatDrawableManager.get().getDrawable(context,arkaPlanID);
on = AppCompatDrawableManager.get().getDrawable(context, onPlanID);
setBackground(d);
}
public void cevir(){
if (cevrilebilir){
if(!acikMi){
setBackground(on);
acikMi = true;
}
else{
setBackground(d);
acikMi=false;
}
}
}
And this is my Java code.
public class GameScreen extends AppCompatActivity {
int sonKart = 0;
int skor = 0;
int hamle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Intent i = getIntent();
final String s = i.getStringExtra("ad");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(s);
GridLayout gr = (GridLayout) findViewById(R.id.grid);
kart kartlar[] = new kart[16];
for (int j = 1; j <= 16; j++) {
kartlar[j - 1] = new kart(this, j);
kartlar[j-1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hamle++;
final kart k = (kart)v;
k.cevir();
if (sonKart >0){
final kart k2 = (kart) findViewById(sonKart);
if (k2.onPlanID==k.onPlanID&&k2.getId()!=k.getId()){
k2.cevrilebilir=false;
k.cevrilebilir=false;
sonKart =0;
skor++;
TextView tv = (TextView) findViewById(R.id.textView3);
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv.setText("Score: "+skor);
tv2.setText("Total moves: "+hamle);
if (skor==8){
Intent i = new Intent(GameScreen.this,scoreboard.class);
i.putExtra("ham",hamle);
i.putExtra("isim",s);
startActivity(i);
//oyun bitti
}
}
else{
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
k2.cevir();
k.cevir();
}
},500);
sonKart =0;
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText("Total moves: "+hamle);
}
}
else{
sonKart = k.getId();
}
}
});
}
for (int j=0;j<16;j++){
int rg =(int) (Math.random()*16);
kart k = kartlar[rg];
kartlar[rg] = kartlar [j];
kartlar[j] = k;
}
for (int j = 0; j < 16; j++)
gr.addView(kartlar[j]);
}
}
to disable click on button
button.setEnabled(false);
This is my code for a button. Whenever i click this the app shuts down!I am unable to understand why it's happening?
In my code, I am trying to check if values from dynamically created EditText field has been stored on my variable array values[] and bValues[];
I looked for many answers here on how to retrieve value from dynamic edittext fields. And I came up with this from my understanding.
Can anyone tell me where am I going wrong? And a corrected demo code will be of help!
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText ainput;
private static Button btn, set;
TextView equal_sign;
private static TableLayout tableLayout;
private static LinearLayout bMatrix;
List<EditText> allEds = new ArrayList<EditText>(a*a);
double[] values = new double[(allEds.size())];
List<EditText> bMatrixValues = new ArrayList<EditText>(a);
double[] bValues = new double[bMatrixValues.size()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
set = (Button)findViewById(R.id.set);
tableLayout = (TableLayout) findViewById(R.id.table1);
equal_sign = (TextView) findViewById(R.id.equal_sign);
bMatrix = (LinearLayout) findViewById(R.id.bMatrix);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
tableLayout.removeAllViews();
createMatrix();
}
});
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < allEds.size(); i++){
values[i] = Double.parseDouble(allEds.get(i).getText().toString());
}
for (int j = 0 ; j < bMatrixValues.size(); j++){
bValues[j] = Double.parseDouble(bMatrixValues.get(j).getText().toString());
}
if (allEds.size() > 0 && bMatrixValues.size() > 0){
Toast.makeText(MainActivity.this, "Main Matrix Values inserted!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Insertion failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void createMatrix() {
int p = 1;
for (int i = 0; i < a; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);
EditText magicField;
for (int j = 0; j < a; j++) {
magicField = new EditText(MainActivity.this);
allEds.add(magicField);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
magicField.setWidth(100);
row.addView(magicField, j);
p++;
}
tableLayout.addView(row, i);
}
bMatrix.removeAllViews();
equal_sign.setText("=");
equal_sign.setTextSize(30);
createBMatrix();
}
private void createBMatrix() {
int id = (a * a) + 1;
for (int s = 0; s < a; s++) {
final EditText b = new EditText(this);
bMatrixValues.add(b);
b.setId(id);
b.setHint("b-" + (Integer.toString(s + 1)));
b.setGravity(Gravity.CENTER);
b.setWidth(100);
bMatrix.addView(b);
id++;
}
}
}
And this is the output screen!
Matrix style edit text field gets created nicely. But when i give values to those fields and click on set value button app shuts down..
I have three buttons and hichever button is selected first is marked with an X whilst the second button selected will be marked with an O and the last button is marked as X again.
If an X is marked then its colour is white, if it's a O then it is marked grey.
Now what I want to do is use the saved instance so that when I rotate the phone, the colours stay the same as they were. What is actually happening is that if I rotate the phone then which ever latest selection was made, all the text reverts to that colour.
So if I press for X and the O and rotate the phone, both X and O will be displayed as the grey colour which is O's colours.
If I then select the last X and rotate the phone, all the letters will be marked as a white colour which is X's colour.
I am unsure if it's the set colour that is causing it or that is remembers who's move it was previously and sets the colour according to that, my question is how to solve it so that all the letters keep their colour on rotation?
private boolean playerOneMove = true;
private Button[][] buttons = new Button[1][3];
private static final String TEXT_COLOR = "textColor";
private String textColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player2);
btnObj1 = findViewById(R.id.button_00);
btnObj2 = findViewById(R.id.button_01);
btnObj3 = findViewById(R.id.button_02);
if (savedInstanceState != null) {
textColor = savedInstanceState.getString(TEXT_COLOR);
if(btnObj1 != null) {
btnObj1.setTextColor(Color.parseColor(textColor));
}
if (btnObj2 != null) {
btnObj2.setTextColor(Color.parseColor(textColor));
}
if (btnObj3 != null) {
btnObj3.setTextColor(Color.parseColor(textColor));
}
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
textColor = "#e8e5e5";
((Button) v).setTextColor(Color.parseColor(textColor));
} else {
((Button) v).setText("O");
textColor = "#737374";
((Button) v).setTextColor(Color.parseColor(textColor));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("playerOneMove", playerOneMove);
outState.putString(TEXT_COLOR, textColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
textColor = savedInstanceState.getString(TEXT_COLOR);
}
The behavior you see it's normal because you save a single textColor which will always be the one which was last set by the user. Instead you could simply iterate over the buttons array and save each button's text color:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
Then in onCreate()(remove the onRestoreInstanceState() method) restore the button's state:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player2);
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID);
if (btnState.equals("X")) {
// this is player X
buttons[i][j].setTextColor(playerX);
} else if (btnState.equals("O")) {
// this is player O
buttons[i][j].setTextColor(playerO);
} else {
// unclicked btn, do you have another color?
}
}
}
}
If you have a greater number of buttons, it may make more sense to group the buttons statuses in a list and save that instead of the individual buttons states.
In a listview, on each row, I have 10 buttons. When any of those buttons pressed, color of the buttons should changed (its like filling the bar based on where you pressed) .
Here is what I've done so far:
I have added references of each button to an ArrayList called buttons.
Also, I have an ArrayList which has colors strings.
This is click listener that is assigned to each button.
This is complete code form my adapter class of the listview.
public class TeacherRatingAdapter extends ArrayAdapter<Votes> {
private ArrayList<String> colors = new ArrayList();
private ArrayList<Button> buttons = new ArrayList<>();
private LayoutInflater inflater;
private ArrayList<Votes> mItems = new ArrayList<>();
private ArrayList<Votes> mItemsTemp = new ArrayList<>();
private int teacher;
private boolean myTeacher;
private ArrayList<Pair<Integer, Integer>> questionHint = new ArrayList<>();
private static int givenMark;
private HashMap<String, Integer> givenMarks = new HashMap<>();
ViewHolder viewHolder;
public TeacherRatingAdapter(Context context, TeacherRating teacherRating) {
super(context, -1, teacherRating.getVotes());
mItems = teacherRating.getVotes();
if(mItems.size()==0){
for(int i = 0; i<10; i++){
mItems.add(new Votes());
}
}
for(int i = 0; i<teacherRating.getVotes().size(); i++){
givenMarks.put(String.valueOf(i+1), teacherRating.getVotes().get(i).getAll().get(i));
}
teacher = teacherRating.getTeacher();
myTeacher = teacherRating.isMy_teacher();
questionHint.add(new Pair<>(R.string.question1, R.string.questionHint1));
questionHint.add(new Pair<>(R.string.question2, R.string.questionHint2));
questionHint.add(new Pair<>(R.string.question3, R.string.questionHint3));
questionHint.add(new Pair<>(R.string.question4, R.string.questionHint4));
questionHint.add(new Pair<>(R.string.question5, R.string.questionHint5));
questionHint.add(new Pair<>(R.string.question6, R.string.questionHint6));
questionHint.add(new Pair<>(R.string.question7, R.string.questionHint7));
questionHint.add(new Pair<>(R.string.question8, R.string.questionHint8));
questionHint.add(new Pair<>(R.string.question9, R.string.questionHint9));
questionHint.add(new Pair<>(R.string.question10, R.string.questionHint10));
colors.add("#E77272");
colors.add("#E77D72");
colors.add("#E78D72");
colors.add("#E7A472");
colors.add("#E8B472");
colors.add("#E8C272");
colors.add("#E8C272");
colors.add("#E6E773");
colors.add("#c3e874");
colors.add("#89e874");
}
#Override
public int getCount() {
return mItems.size() > 0 ? mItems.size() : 1;
}
#Override
public boolean isEnabled(int position) {
return mItems.size() != 0;
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button = (Button) v;
String text = button.getText().toString();
if(text.equals("1")){
givenMark = 1;
}else if(text.equals("2")){
givenMark = 2;
}else if(text.equals("3")){
givenMark = 3;
}else if(text.equals("4")){
givenMark = 4;
}else if(text.equals("5")){
givenMark = 5;
}else if(text.equals("6")){
givenMark = 6;
}else if(text.equals("7")){
givenMark = 7;
}else if(text.equals("8")){
givenMark = 8;
}else if(text.equals("9")){
givenMark = 9;
}else if(text.equals("10")){
givenMark = 10;
}
colorButton(givenMark, viewHolder);
// button.setBackgroundColor(Color.parseColor(colors.get(givenMark)));
mItems.get(Integer.valueOf(button.getTag().toString())).addOne(Integer.valueOf(text));
// mItems.get(Integer.valueOf(button.getTag().toString())).setScore(Integer.valueOf(text), givenMark);
// givenMarks.put(button.getTag().toString(), givenMark);
notifyDataSetChanged();
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = LayoutInflater.from(getContext());
if (mItems.size() == 0) {
if (!Common.isNetworkConnected(getContext())) {
convertView = inflater.inflate(R.layout.list_item_no_internet, null, false);
} else {
convertView = inflater.inflate(R.layout.list_item_no_content, null, false);
}
return convertView;
} else {
if (convertView == null) {
buttons.clear();
convertView = inflater.inflate(R.layout.list_item_teacher_rating, parent, false);
viewHolder = new ViewHolder();
viewHolder.mQuestionTextView = (TextView) convertView.findViewById(R.id.question);
viewHolder.mHintTextView = (TextView) convertView.findViewById(R.id.question_hint);
viewHolder.button1 = (Button) convertView.findViewById(R.id.question_button_1);
viewHolder.button2 = (Button) convertView.findViewById(R.id.question_button_2);
viewHolder.button3 = (Button) convertView.findViewById(R.id.question_button_3);
viewHolder.button4 = (Button) convertView.findViewById(R.id.question_button_4);
viewHolder.button5 = (Button) convertView.findViewById(R.id.question_button_5);
viewHolder.button6 = (Button) convertView.findViewById(R.id.question_button_6);
viewHolder.button7 = (Button) convertView.findViewById(R.id.question_button_7);
viewHolder.button8 = (Button) convertView.findViewById(R.id.question_button_8);
viewHolder.button9 = (Button) convertView.findViewById(R.id.question_button_9);
viewHolder.button10 = (Button) convertView.findViewById(R.id.question_button_10);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button2.setOnClickListener(clickListener);
viewHolder.button3.setOnClickListener(clickListener);
viewHolder.button4.setOnClickListener(clickListener);
viewHolder.button5.setOnClickListener(clickListener);
viewHolder.button6.setOnClickListener(clickListener);
viewHolder.button7.setOnClickListener(clickListener);
viewHolder.button8.setOnClickListener(clickListener);
viewHolder.button9.setOnClickListener(clickListener);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button1.setTag(position);
viewHolder.button2.setTag(position);
viewHolder.button3.setTag(position);
viewHolder.button4.setTag(position);
viewHolder.button5.setTag(position);
viewHolder.button6.setTag(position);
viewHolder.button7.setTag(position);
viewHolder.button8.setTag(position);
viewHolder.button9.setTag(position);
viewHolder.button1.setTag(position);
buttons.add(viewHolder.button1);
buttons.add(viewHolder.button2);
buttons.add(viewHolder.button3);
buttons.add(viewHolder.button4);
buttons.add(viewHolder.button5);
buttons.add(viewHolder.button6);
buttons.add(viewHolder.button7);
buttons.add(viewHolder.button8);
buttons.add(viewHolder.button9);
buttons.add(viewHolder.button10);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mQuestionTextView.setText(questionHint.get(position).getValue0());
viewHolder.mHintTextView.setText(questionHint.get(position).getValue1());
Votes item = getItem(position);
int count = 0;
double score = 0;
for(int i = 0; i<item.getAll().size(); i++){
score += (i+1) * item.getAll().get(i);
count +=item.getAll().get(i);
}
if(count>0){
score = score/count;
}
if(score==0){
score = 10;
}
// double diff = (10-Math.round(score));
colorButton(Math.round(score), viewHolder);
// colorButton((int) score);
// for (int j = 9; j >= diff; j--) {
// Button button = buttons.get(j);
// button.setBackgroundColor(Color.WHITE);
// button.setTextColor(Color.BLACK);
// }
}
return convertView;
}
private void colorButton(long givenMark, ViewHolder viewHolder){
for(int i=0; i<buttons.size();i++){
buttons.get(i).setBackgroundColor(Color.WHITE);
}
for (int j = 0; j <= givenMark; j++) {
Button button = buttons.get(j);
button.setBackgroundColor(Color.parseColor(colors.get(j)));
}
}
private static class ViewHolder {
TextView mQuestionTextView;
TextView mHintTextView;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button button10;
}
}
It looks like this:
So, when I press button 3, all colors beyond 3, must become white. Or when I press button 9, all buttons before it must have its colors, and buttons in fron of it must be white. But this does not happen, and there is no error.
Thank you for any help.
Isn't that rating bar?
OnClickListener is wrong, I meant not the right listener, you got the idea wrong. What's the enclosing View?
I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener