Android Studio静态或非静态变量和方法

时间:2015-10-17 05:09:06

标签: android static non-static

我对变量或方法应该是静态的时候有点困惑。我开发了一个包含多个类,变量和方法的应用程序,很少使用关键字static。但它的工作令人满意。你能告诉我,我是否犯了错误,为什么。以下是我的代码示例:

public class GameActivity extends AppCompatActivity {

public String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
        "DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
        "LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
        "SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
        "WEST","WHEN","WOMAN","YOUNG"};

public String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
        "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};

public String mysteryWord = "vide";
//public int nombreDeLettres;

public int numeroImage = 1;
public boolean jeuFini = false;
public int lettresDevinees = 0;
public int wins = 0;
public int losses = 0;

public int numberOfMots;
int numeroAuHasard;
public Boolean maLettreAServi = false;
public ArrayList<CharSequence> lettresEssayees = new ArrayList<>();

public Button monBouton;
public TextView monTextView;


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

    AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest request = new AdRequest.Builder()
            .addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4")  // adds my test phone
            .build();
    mAdView.loadAd(request);

    // une des solutions pour rendre la zone trado scrollable
    TextView myXmlContent = (TextView)findViewById(R.id.zone_trado_scrollable);
    myXmlContent.setMovementMethod(new ScrollingMovementMethod());

    // écouteurs de tous les boutons actifs
    ecouteursDeBoutons();

}


// joue une lettre
public void playLetter(final String letter) {

    Resources res = getResources();
    final int resId = res.getIdentifier(letter, "id", getPackageName());
    monTextView = (TextView) this.findViewById(R.id.zone_trado_scrollable);

    final TextView maLettre = (TextView) this.findViewById(resId);
    maLettre.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!jeuFini) { // il faut mettre ce test _dans_ le onClick(View v)

                if (!mysteryWord.equalsIgnoreCase("vide")) {

                    if (!lettresEssayees.contains(maLettre.getText())) {
                        // on teste que la lettre n'a pas déjà été essayée

                        maLettreAServi = false;

                        // boucle de test de lettre
                        for (int i = 0; i < mysteryWord.length(); i++) {
                            if (String.valueOf(mysteryWord.charAt(i)).equals(maLettre.getText())) {

                                int j = i + 1; // car dans le layout xml les id des positions commencent à 1

                                //monTextView.append("\nyou correctly found " + maLettre.getText() + " at position " + j);

                                final int resId = getResources().getIdentifier("position" + j, "id", getPackageName());
                                final TextView lettreADeviner = (TextView) GameActivity.this.findViewById(resId);
                                lettreADeviner.setText(maLettre.getText());

                                maLettreAServi = true;

                                lettresDevinees++;
                            }
                        }

                        maLettre.setText(""); // on efface de l'alphabet la lettre essayée

                        lettresEssayees.add(maLettre.getText());
                        // on la met dans l'arraylist lettresEssayees
                        // afin de ne pas la réessayer
                        // noter que java comprend qu'il s'agit d'un caractère et non d'une string


                        // test pour effacer de l'alphabet une lettre qui a servi
                        if (!maLettreAServi) {

                            // incrémenter le pendu
                            numeroImage++;

                            if (numeroImage < 10) {
                                ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
                                final int imageId = getResources().getIdentifier("pendu" + numeroImage, "drawable", getPackageName());
                                monImage.setImageResource(imageId);
                            } else {
                                ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
                                final int imageId = getResources().getIdentifier("pendu10", "drawable", getPackageName());
                                monImage.setImageResource(imageId);

                                jeuFini = true;
                                monTextView.setText(Html.fromHtml("<font color=\"red\">you lost</font>"));
                                monTextView.append("\nthe word was "+mysteryWord);

                                losses++;
                                TextView nombrePertes = (TextView) findViewById(R.id.nr_losses);
                                nombrePertes.setText("" + losses); // pas réussi à utiliser toString(), alors j'utilise cette converstion
                            }
                        }

                        // test qu'on a trouvé le mot mystère
                        if (lettresDevinees == mysteryWord.length()) {
                            jeuFini = true;


                            // randomisation des félicitations
                            Random generator = new Random();
                            int randomIndex = generator.nextInt(3);

                            if(randomIndex == 0){
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">bravo!</font>"));}

                            else if(randomIndex == 1){
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">fantastic!</font>"));}

                            else if (randomIndex == 2) {
                            monTextView.setText(Html.fromHtml("<font color=\"blue\">you won</font>"));}


                            // rappel de ce qu'était le mot à deviner
                            monTextView.append("\nthe word was indeed " + mysteryWord);

                            String son = mysteryWord.toLowerCase()+"1";

                            final int resRaw = getResources().getIdentifier(son, "raw", getPackageName());
                            final MediaPlayer mp = MediaPlayer.create(GameActivity.this, resRaw);
                            mp.start();

                            wins++;
                            TextView nombreGains = (TextView) findViewById(R.id.nr_wins);
                            nombreGains.setText("" + wins); // pas réussi à utiliser toString(), alors j'utilise cette converstion
                        }
                    }

                } else {
                    monTextView.setText("click on Select word first");
                }
            }
        }
    });
}

...

}

6 个答案:

答案 0 :(得分:8)

java中的static关键字主要用于内存管理。我们可以将java static keyword与变量,方法,块和嵌套类一起应用。 如果我们谈论静态变量,那么我们将其区分为 静态变量可用于引用所有对象的公共属性(对于每个对象而言不是唯一的),例如公司员工姓名,学生姓名等。

静态变量在类加载时只在类区域中获取一次内存。

如果我们谈论它使用: 当你想要共享你的变量或方法时,只需要在整个类中单个副本而不创建不同的副本,你应该使用static。

<强>优点 它使程序存储器有效(即节省内存)。

答案 1 :(得分:1)

可以使用类名直接访问静态变量,它将具有单个实例。

YourActivity.staticVariableName=something;

从应用程序的任何位置访问变量很有帮助。但请注意,在整个应用程序结束之前,它有一生。因此它在整个应用程序生命周期内消耗该内存。因此,请牢记这一点。

答案 2 :(得分:1)

通常,所有与类对象无关且适用于整个对象的常量和变量都应声明为static。因此,查看示例代码时,您应该将motsalphabet声明为staticfinal,因为没有必要为您的每个对象都单独复制这些代码。

如果你想在其他地方使用GameActivity关键字,那么关键字static也允许你通过使用GameActivity.mots类名final来访问其他类中的这些常量,public final static String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY", "DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER", "LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE", "SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY", "WEST","WHEN","WOMAN","YOUNG"}; public final String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M", "N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; 关键字可以保证没有人可以改变这些。

<div class="form-group">
    <label for="Course" class="col-sm-4 control-label">Dashbord *</label>
    <div class="col-sm-4" id="multicourse">
        <select id="Course" name="options[]" multiple="multiple"  style="width:100%">

            <option value="1"  >Sales</option>
            <option value="2" >Students</option>
            <option value="3" >Quetion</option>
            <option value="4" >Test</option>
            <option value="5" >Test Series</option>
            <option value="6" >Student</option>
            <option value="7" >Validity</option>
            <option value="8" >Disk Space</option>
            <option value="9" >Student Graph</option>
            <option value="10"  >Date</option>

        </select>
    </div>
</div>

答案 3 :(得分:1)

我只想在 pgiitu Piyush Gupta 的答案中添加另一个观点。

根据Java docs如果您的变量存储一个常量值,例如static final int NUM_GEARS = 6,则约定会略有变化,将每个字母大写并用后缀字符分隔后续单词。按照惯例,下划线字符从未在别处使用过。

因此,正如 pgiitu 所提到的motsalphabet应该声明为staticfinal。但是,通过命名约定,您应该将它们分别重命名为MOTSALPHABET

答案 4 :(得分:0)

当你想要共享你的变量或方法时,只需要通过类复制而不创建不同的副本,你应该使用static ..而且接口变量默认是static和final。如果你想了解更多

,首先应该选择基本的JAVA概念

答案 5 :(得分:0)

当您想要单个变量在您的应用中使用多个位置时,基本上使用

静态变量。类似静态方法的概念。 了解更多信息请点击此链接  http://www.javatpoint.com/static-keyword-in-java