2016-06-28 14 views
0

我正在嘗試創建一個遊戲日誌,以顯示遊戲的每一輪發生的事情。日誌在另一個活動中,但我希望隨着玩家的操作不斷更新。玩家只需按下執行某些操作的按鈕即可。發佈的代碼太多,但是我已經制作了一個新的包和一個意圖。通過主追加另一個活動的TextView

In MainActivity。

Bundle bundle = new Bundle(); 
Intent GameLogSwitch = new Intent(getApplicationContext(),GameLog.class); 

我想把這個發送到其他活動,但我不知道你是否可以把變量放在裏面。否則它與簡單的詞語,如(「鑰匙」,「它的工作原理」)

GameLogSwitch.putExtra("Break","---BREAK---"+"\n"+Player1Name+": "+GreenResult.getText()+"("+GrTop1+","+GrTop2+","+GrTop3+")"+"\n"+Player2Name+": "+RedResult.getText()+"("+RdTop1+","+RdTop2+","+RdTop3+")"); 

,然後我當然這個時候gamelog按鈕Gamelog.class按下

​​

現在我有這個。

package com.example.adam.snookerproject; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.widget.TextView; 

public class GameLog extends AppCompatActivity { 
     private TextView GameLogText; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game_log); 
     GameLogText = (TextView) findViewById(R.id.GameLogText); 
     Intent GameLogSwitch = getIntent(); 
     String myString = GameLogSwitch.getStringExtra("Break"); 
     GameLogText.append(myString); 
    } 
} 

我有幾個問題。首先,當我開始活動時,爲什麼只在我的字符串中追加一次,即當我再次返回並再次按下相同的按鈕時,它不會在下面再次寫入相同的內容?

其次,它似乎不適用於我的「休息」鍵,這是否與我發送的文本中存在變量這一事實有關?它只適用於簡單文本,如GameLogSwitch.putExtra("key","It works");

必須有一個更簡單的方法來做到這一點!謝謝。

更新1:從Drv的答案似乎工作,但是當我嘗試做GameLogText.append(AppConstants.log)它只是替換textview中的所有內容,無論我按了多少次按鈕。我認爲每次重新開始時,活動都會重置。任何方式在這個?

+0

tl; dr。您最好查看EventBus庫,它會讓您的生活變得更加輕鬆,因爲它可以讓您將數據從任何地方異步發送到任何地方。 – Vucko

+2

http://square.github.io/otto/ – anivaler

+0

嗯不好意思看看那個。 – deathskiller

回答

1

請在常量類中的全局字符串,並使用它,無論你想:

public class AppConstants{ 

     public static String log=""; 
    } 

編輯字符串中的類,你要發送它的意圖:

AppConstants.log="---BREAK---"+"\n"+Player1Name+": "+GreenResult.getText()+"("+GrTop1+","+GrTop2+","+GrTop3+")"+"\n"+Player2Name+": "+RedResult.getText()+"("+RdTop1+","+RdTop2+","+RdTop3+")"; 

而且用它您的課程爲:

package com.example.adam.snookerproject; 

    import android.content.Intent; 
    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.widget.TextView; 

    public class GameLog extends AppCompatActivity { 
    private TextView GameLogText; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game_log); 

     GameLogText = (TextView) findViewById(R.id.GameLogText); 

     //get your log here using AppConstants.log 
    } 
    } 
+0

這對我的問題的第一部分似乎有效,謝謝! – deathskiller

0

嘗試使用getContext()代替getApplicationContext,然後檢查您r string in debug mode

0

(發佈代表OP的溶液)

我設法使用"\n"+AppConstants.log附加在每個輸出結束。

相關問題