2011-08-16 15 views
2

該課程具有我想要發送的意向另一個活動的信息。當按下圖像按鈕「超人」時,onClick()處理程序將意圖發送給SuperheroActivity。但是當我嘗試在其他活動中檢索這些信息時,我會收到「假」的信息。試圖發送一個意圖的視圖的ID。獲得「虛假」

public class MenuActivity extends Activity implements 
    OnClickListener { 
private ImageButton superman; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.menu); 

    superman = (ImageButton) findViewById(R.id.superman); 
    superman.setOnClickListener(this); 
} 

@Override 
public void onClick(View v) { 
    Intent intent = new Intent(MenuActivity.this, SuperheroActivity.class); 
    intent.putExtra("id", v.getId()); 
    startActivity(intent); 
} 

}

這是一段代碼,試圖檢索從意圖的信息。注意:這是SuperheroActivity。

Intent intent = getIntent(); 
id = intent.getIntExtra("id", 0); 
// This is just a dirty way for me to see the value of the id I am getting. 
TextView text = (TextView) findViewById(R.id.superheroText); 
text.setText(id); 

回答

1

錯誤在這行代碼中。

text.setText(id); 

表示資源ID(即String資源ID)。 嘗試替換並使用此。

text.setText(String.valueOf(id)); 
+0

setText方法被重載以獲取字符串資源ID作爲參數。 – Ronnie

+0

是的,它被超載。 –

1

使用getExtras()

Intent intent = getIntent(); 
id = intent.getExtras().getInt("id"); 

記住你不能setText(int)獲取包!在int必須是String

因此改變

TextView text = (TextView) findViewById(R.id.superheroText); 
text.setText(id); 

TextView text = (TextView) findViewById(R.id.superheroText); 
text.setText(String.valueOf(id)); //change id to a string 
+0

的setText方法被重載採取字符串資源id作爲參數。 – Ronnie

1

使用ID = intent..getExtras()。getInt( 「ID」),從意向獲取數據。 ..

1

SuperheroActivity

Bundle extras = getIntent().getExtras(); 
id = extras.getInt("id"); 
TextView text = (TextView) findViewById(R.id.superheroText); 
text.setText(id+""); 
相關問題