首页 > 解决方案 > 在其他活动中调用一个类并更改其变量之一

问题描述

我正在做一个简单的游戏,我有 3 个级别。我完成了activity1中的level1。但是由于 level2 中的代码除了一个变量之外是相同的,所以我想在 activity2(level2) 中扩展 level1 类,但是我的类已经在扩展 Activity 类并且在 java 中无法同时继承两个类,所以我决定在 activity2(level2) 中创建一个类的对象并在 onCreate () 中对其进行初始化,但是我面临一个问题,我有一个字符串数组变量,它在 level1 中包含 100 个单词,我想添加另一个100 到该字符串,使其在 level2 中为 200。我怎样才能做到这一点。我不想在 level2 中复制 level 1 的整个代码,然后只是更改变量,这是冗余,一种不好的做法。

这是我的意思的原型。

活动 1,级别 1。并在 Activity2 下方,级别 2

  public class Level1 extends Activity {
      String words[ ] = {ball, game, food, bike, ...... ..}
        //100  words
          protected void on create(Bundle b){
          super.onCreate(b);
          setContentView(R.layout. level1)

             }
          }



     public class level2 extends Activity{
        Level1 level;
         protected void onCreate (Bundle b){
         super.onCreate(b);
         setContentView(R.layout.level2);
         level = new Level1();
           //how can l add 100 more word in the string arrived 
              here
           }
       }

标签: javaandroid

解决方案


Try to separate the data (words) from the UI (Activity) first. Create a class that is responsible for providing the data for the Activities.

public class WordsProvider {

    private String wordsForLevel1[] = {ball, game, food, bike, ...... ..};
    private String wordsForLevel2[] = {words, you, want, to, add, to, first, array};

    public String[] getWordsForLevel1() {
        return wordsForLevel1;
    }

    public String[] getWordsForLevel2() {
        return concat(wordsForLevel1, wordsForLevel2);
    }
}

(concat method can be found here)

Now, you don't have to couple your Activities. Instantiating an Activity manually is not recommended, let the Android System do that work. So your code will look like this:

public class Level1 extends Activity {
    String words[];

    protected void on create(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.level1)
        words = new WordsProvider().getWordsForLevel1();
    }
}

public class Level2 extends Activity {
     String words[];

     protected void onCreate (Bundle b) {
         super.onCreate(b);
         setContentView(R.layout.level2);
         words = new WordsProvider().getWordsForLevel2();
    }
}

I hope it helps for you!


推荐阅读