0

嘿大家希望你能帮助解决这个问题,感谢您查看我的 Q。我需要更新

public static int hScoreGen1 = 0; (activity A)

来自另一个活动(活动 B)。的值hScoreGen1显示在活动 A 的列表视图中

//Activity A

public void setList1(){

        HashMap<String,String> temp = new HashMap<String,String>();
        temp.put("catGeneral","Level 1");
        temp.put("score1", String.valueOf(hScoreGen1) + "/10");
        listGeneral.add(temp);
        }

//Activity A    

adapter1 = new SimpleAdapter(
                    this,

                listGeneral,
                R.layout.list_highscore_row,
                new String[] {"catGeneral","score1"},
                new int[] {R.id.text1,R.id.text2}
        );

//Activity A
public static  SimpleAdapter adapter1;

这改变了价值

Activity B

if (totalCorrect > ScoreScreen.currentScoreCatValue){

                                HighScores.hScoreGen1 = totalCorrect;
                                HighScores.adapter1.notifyDataSetChanged();

                        }

有人告诉我,将适配器设为静态可能会导致泄漏。而对于侦听器,只需创建一个接口,在我要更新分数的 Activity 上实现它。在基本活动中设置此侦听器对象 [应用空检查] 并从第二个活动设置侦听器。听起来不错,但找不到这样的代码示例....如果您有任何想法,他们将不胜感激。

4

1 回答 1

0

一种可能的解决方案是使用存储 int hScoreGen1的Singleton类:

public class Singleton {

    private static Singleton instance;
    public static int hScoreGen1 = 0;

    private Singleton() {
    }

    public static Singleton getInstance() {

        if (instance == null)
            instance = new Singleton();
        return instance;
    }

    public void setScore(int score) {

        this.hScoreGen1 = score;
    }

    public int getScore(int score) {

        return this.hScoreGen1;
    }    
}

这样,您的变量hScoreGen将只初始化一次,您将能够在 A 中设置它的值Activity并在 B 中显示它Activity

public class ActivityA extends Activity {

    @Override
    public void onCreate(...) {
        Singleton score = Singleton.getInstance();
        score.setScore(10);

        ...
    }
}



public class ActivityB extends Activity {

    @Override
    public void onCreate(...) {
        Singleton score = Singleton.getInstance();
        TextView textView = (TextView) findViewById(R.id.text_view);
        textView.setText(score.getScore());

        ...
    }
}
于 2014-04-23T13:35:55.747 回答