[英]how to implement a listener on an activity to update a listview adaptor
大家好,希望您能為您提供幫助,感謝您關注我的問題。我需要更新的價值
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上實現此接口。 在基本活動中設置此偵聽器對象[應用null檢查],並在第二個活動中設置偵聽器。 聽起來不錯,但是康特找到了這樣的代碼示例。...如果您有任何想法,將不勝感激。
一種可能的解決方案是使用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());
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.