如何在活动上实现侦听器以更新listview适配器

时间:2014-04-23 13:10:28

标签: java android android-activity listener adaptor

嘿大家都希望你能帮忙解决这个问题并感谢你看看我的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上实现它。在基本活动中设置此侦听器对象[应用空检查]并从第二个活动设置侦听器。这听起来是对的,但是找不到这个代码的例子....如果你有任何想法,他们将不胜感激。

1 个答案:

答案 0 :(得分:0)

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

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 只会初始化一次,您可以在Activity A中设置其值,并将其显示在Activity B中:

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());

        ...
    }
}