简体   繁体   中英

Android: pass variables to/out button anonymous class

package com.example.rami.androidstudio_312332604_guessgame;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity {
    ArrayList<Character> lettersguessed = new ArrayList<Character>();
    int counter = 6;

    private String changeCharInPosition(int position, char ch, String str) {
        char[] charArray = str.toCharArray();
        charArray[position] = ch;
        return new String(charArray);
    }

    private void start() {
        TextView errortext = (TextView) findViewById(R.id.statustext);
        Button button = (Button) findViewById(R.id.guessbt);
        TextView tv = (TextView) findViewById(R.id.guessingtext);//get the textview from the activity
        TextView testtext = (TextView) findViewById(R.id.testtext);//get the testview from the activity
        EditText edittext = (EditText) findViewById(R.id.editText);
        String[] world = getResources().getStringArray(R.array.words);// get the array from string xml
        Random rand = new Random();
        errortext.setText("");
        int randomNum = rand.nextInt(world.length);
        String country = world[randomNum];
        String s = "";
        for (int i = 0; i < country.length(); i++) {
            if (country.charAt(i) != ' ')
                s += '?';
            else
                s += ' ';
        }
        tv.setText(s);
        testtext.setText(world[randomNum]);
        button.setEnabled(true);
        //Toast toast = Toast.makeText(getApplicationContext(), points, Toast.LENGTH_LONG);
        //toast.show();
    }

    // Remove the below line after defining your own ad unit ID.
    private static final String TOAST_TEXT = "Test ads are being shown. "
            + "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        start();


        Button button = (Button) findViewById(R.id.guessbt);

        button.setOnClickListener(new View.OnClickListener() {

            ArrayList<Character> lettersguessed = new ArrayList<Character>();
            int counter = 6;

            private void clear() {
                ImageView img = (ImageView) findViewById(R.id.errorimg);
                TextView errortext = (TextView) findViewById(R.id.statustext);
                img.setImageResource(R.mipmap.error_num0);
                counter = 6;
                lettersguessed.clear();
                errortext.setText("");
            }

            public void onClick(View v) {

                EditText guessedtext = (EditText) findViewById(R.id.editText);
                Button button = (Button) findViewById(R.id.guessbt);
                TextView questionstext = (TextView) findViewById(R.id.guessingtext);
                TextView errortext = (TextView) findViewById(R.id.statustext);


                if (guessedtext.getText().length() != 1) {//to make sure it's one char
                    Toast toast = Toast.makeText(getApplicationContext(), "Please Enter One Char", Toast.LENGTH_SHORT);
                    toast.show();
                    guessedtext.setText("");
                    return;
                }

                String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
                char uc = Character.toUpperCase(guessedtext.getText().charAt(0));
                char lc = Character.toLowerCase(guessedtext.getText().charAt(0));
                guessedtext.setText("");
                if (lettersguessed.contains(uc)) {
                    Toast toast = Toast.makeText(getApplicationContext(), "You tried that before", Toast.LENGTH_SHORT);
                    toast.show();
                    return;
                }
                lettersguessed.add(uc);
                boolean right = false;
                for (int i = 0; i < country.length(); i++) {
                    char cc = country.charAt(i);
                    if (cc == uc || cc == lc) {
                        right = true;
                        questionstext.setText(changeCharInPosition(i, cc, questionstext.getText().toString()));
                        errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
                    }
                }
                if (!right) {
                    if (counter == 1) {
                        Toast toast = Toast.makeText(getApplicationContext(), "Game Over", Toast.LENGTH_SHORT);
                        toast.show();
                        clear();
                        //points=-20;
                        return;
                    }
                    ImageView img = (ImageView) findViewById(R.id.errorimg);
                    counter--;
                    img.setImageResource(R.mipmap.error_num1);
                    errortext.setText("You have guessed: " + lettersguessed.toString() + " (" + counter + " tries left)");
                }
                if (questionstext.getText().toString().indexOf('?') < 0) {
                    Toast toast = Toast.makeText(getApplicationContext(), "Done it!", Toast.LENGTH_SHORT);
                    toast.show();
                    button.setEnabled(false);
                    clear();
                    //points += 20;
                    return;
                }
            }
        });
        Button newtb = (Button) findViewById(R.id.newbt);
        newtb.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                start();

            }
        });

        Button giveupbt = (Button) findViewById(R.id.giveupbt);
        giveupbt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Button button = (Button) findViewById(R.id.guessbt);
                String country = ((TextView) findViewById(R.id.testtext)).getText().toString();
                TextView guessedtext = (TextView) findViewById(R.id.guessingtext);
                guessedtext.setText(country);
                button.setEnabled(false);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
  ArrayList<Character> lettersguessed = new ArrayList<Character>(); int counter = 6; 

**These two variables, I want to reach or to make this class vars and reach them from the anonymous class. Because I want to read this and change their value

More info: the button is the guessing button for guessing countries names game and after entering the char into edittext you click this button to make your guess.

Any Ideas?

Just make these two variables as final and then access them in your inner class. So it then becomes,

final ArrayList<Character> lettersguessed = new ArrayList<Character>();
final int[] counter = new int[1];
counter[0] = 6;

just replace counter by counter[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM