簡體   English   中英

Android從mainActivity的所有片段中刷新TextViews

[英]Android refresh TextViews in all fragments from mainActivity

無法理解如何刷新/更新我所有的文本視圖。 它們位於13個不同的片段中,我無法按自己的意願接受它們。

在簡單的Java中,我得到了一個簡單的游戲循環

//Game Loop
            boolean GameLoop = true;
            while(GameLoop){
            CG.refresh();
            }    

在主班我得到了這樣的東西:

void refresh() {            
    Labels.MoneyLabel.setText("Money: " + CarMain.main[0]);
    Labels.BoxesLabel.setText("Boxes: " + CarMain.main[2]);

}

而且這一切都奏效。 現在在Android中,我無法更新我的文本視圖。

在Android上,onCreate方法使游戲循環變得簡單

     Thread t = new Thread() {

        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Collections();
                            SaveFile();
                            Refresh();
                        }
                    });
                }
            } catch (InterruptedException e) {
            }
        }
    };

    t.start();

並希望刷新像

公共無效Refresh(){

 TextView MoneyTXT = (TextView) rootView.findViewById(R.id.MoneyText);
            MoneyTXT.setText("Money: " + Main.Money[0]);
            TextView  MoneyPerTapTXT = (TextView) rootView.findViewById(R.id.MoneyPerTapTView);
            MoneyPerTapTXT.setText("$ " + Main.Money[1] + " per tap");
                TextView BoxesTXT = (TextView) rootView.findViewById(R.id.BoxesText);
                BoxesTXT.setText("Boxes: " + Main.Boxes[0]);
                TextView BoxesPerTapTXT = (TextView) rootView.findViewById(R.id.BoxesPerTapTView);
                BoxesPerTapTXT.setText("Points " + Main.Boxes[1] + " per tap");

}

但是出錯了,因為Textviews位於不同的布局中。

要從活動中更新片段:

假設您的片段已添加到ID為R.id.frame的視圖中,則可以執行以下操作:

// Get current Fragment   
Fragment fragment = getFragmentManager().findFragmentById(R.id.frame);
if (fragment instanceof MyFragment) { //or whatever your Fragment's name is
    ((MyFragment) fragment).updateTextView(); // This is a method you will have to define yourself
}

那有意義嗎?

如果您不希望通過方法回調機制進行處理,則可以使用GreenRobot EventBus之類的第三方庫嘗試事件回調機制。

簡單的例子

定義事件:

public static class MessageEvent { /* Additional fields if needed */ }

准備訂閱者:(訂閱您的活動以接收事件)聲明並注釋您的訂閱方法,可以選擇指定線程模式:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

注冊和注銷您的訂戶。 例如,在Android上,活動和片段通常應根據其生命周期進行注冊:

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    super.onStop();
    EventBus.getDefault().unregister(this);
}

發布事件:(單擊片段按鈕發布事件,活動將立即得到通知)

EventBus.getDefault().post(new MessageEvent());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM