【问题标题】:how to implement a listener on an activity to update a listview adaptor如何在活动上实现侦听器以更新列表视图适配器
【发布时间】:2014-04-23 13:10:28
【问题描述】:

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

【问题讨论】:

    标签: java android android-activity listener adaptor


    【解决方案1】:

    一个可能的解决方案是使用一个 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 只会被初始化一次,你就可以在ActivityA 中设置它的值并在ActivityB 中显示它:

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

    【讨论】:

    • 很有趣,但它们肯定是一种更简单的方法,因为我只改变了一个 var 的值。广播接收器会更简单
    • 好的,我明白了。 This link 如果您还没有看到它可能会有所帮助。我个人总是使用那里描述的那种方法而不是使用广播:)。
    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2018-06-27
    相关资源
    最近更新 更多