2013-04-14 91 views
0

我是新來的android,所以也許我做了一些可怕的錯誤。我想要一個特定的活動來顯示關於遊戲「生物」類的實例的詳細信息。名稱,受到的傷害,諸如此類的事情。活動沒有正確更新

我有一個問題讓生物數據在GUI對象中正確顯示。在初始創建時(應將生物名稱複製到名稱字段中)以及添加損壞標記(未更新時顯示正確圖像)。

這裏是什麼,我有我的小例子:

public class CreatureDetailActivity2 extends Activity 
{ 
    Creature creature; 

    public void addMark(View v) 
    { 
    // connected to the button via android:onClick="addMark" in the XML 
    creature.getTrack().addDamage(DamageType.Normal, 1); 
    refreshDisplay(); 
    new AlertDialog.Builder(this).setTitle(creature.getName()) 
     .setMessage(creature.getTrack().toString()).show(); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_creature_detail); 
    creature = new Creature("Example"); 
    refreshDisplay(); 
    } 


    public void refreshDisplay() 
    { 
    final View creatureDetailView = this.getLayoutInflater().inflate(
     R.layout.activity_creature_detail, null); 

    final EditText nameField = (EditText) (creatureDetailView 
     .findViewById(R.id.textbox_creature_name)); 
    nameField.setText(creature.getName()); 

    final ImageView damageBox0 = (ImageView) (creatureDetailView.findViewById(R.id.damageBox0)); 
    damageBox0.setImageResource(R.drawable.__n); 
    // in the full program this does the same for 0 through 9, but this is a sample 
    // also, in the full program, this is a dynamic lookup for the correct pic 
    // but again, this is just a sample version. 
    } 
} 

現在的問題是,該應用程序將加載和啓動,但隨後沒有任何部件都將正確更新。您可以單擊按鈕,它將顯示AlertDialog,並且AlertDialog的文本將會更改,但活動中的文本字段將不會更改,並且ImageView在任何時候都不會更改到它應該改變的那個。

所以我非常難過。如果我遺漏了一些重要的東西,我可以發佈更多關於該項目的設置,但我甚至不知道問題所在是什麼,所以我不確定我的問題還包括什麼。

回答

2
final View creatureDetailView = this.getLayoutInflater().inflate(
     R.layout.activity_creature_detail, null); 

膨脹你的活動的佈局基本上什麼都沒有,只是返回查看它膨脹。 setContentView實際上是將佈局擴展到Activity的View層次結構中。

一旦你膨脹你的佈局,你不需要再做一次。只要使用findViewById而不涉及懸掛的獨立視圖。

您refreshDisplay方法改成這樣:因爲你這樣做完全錯誤

public void refreshDisplay() 
{ 
    final EditText nameField = (EditText) findViewById(R.id.textbox_creature_name); 
    nameField.setText(creature.getName()); 

    final ImageView damageBox0 = (ImageView) findViewById(R.id.damageBox0); 
    damageBox0.setImageResource(R.drawable.__n); 
    // in the full program this does the same for 0 through 9, but this is a sample 
    // also, in the full program, this is a dynamic lookup for the correct pic 
    // but again, this is just a sample version. 
} 
1

沒有什麼變化。

如果您想更新當前活動的任何視圖元素你不喜歡這樣

View v = findViewById(R.id.element); 
v.setText("text"); 

這僅僅是簡單的例子。 您需要將返回的元素轉換爲正確的類型,以便能夠訪問所有可用的方法。

你做錯了什麼是試圖再次膨脹佈局。