[英]Can't update TextView from another activity
我有一個TextView的活動,需要從第二個活動更新。 我可以將Text視圖數據傳遞給第二個活動,但是當我嘗試在第二個活動中更新TextView時它會崩潰。 我的代碼:
第一個Activity(TextView在我的xml中定義):
Intent intent = new Intent(1stactivity.this, 2ndactivity.class);
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
startActivity(intent);
// code snippet
然后在我的第二個活動中:
Bundle bundle = getIntent().getExtras();
hometext = bundle.getString("homescore_value"); // this works and displays the correct String from 1st activity,
但是當我嘗試作為TextView
引入時它會崩潰:
// other code snipped
int homescore = 0;
String Home_nickname = "HOME ";
TextView homestext = (TextView) bundle.get("homescore_value");
hometext.setText(Home_nickname +": "+homescore );
請幫忙。
您正在嘗試將String作為TextView(您在第一個Activity的intent中設置String)。
您嘗試將String
TextView
為TextView
。 崩潰的代碼相當於:
String text = bundle.get("homescore_value"); //this is ok
TextView textView = (TextView)text; //this is bad
你應該這樣做:
String text = bundle.get("homescore_value");
TextView textView = (TextView)findViewById(R.id.yourTextViewId);
textView.setText(text);
這一行在這里:
intent.putExtra("homescore_value", ((TextView)findViewById(R.id.score_home)).getText());
附加一個字符串和意圖,而不是TextView。
您必須通過在layout.xml中聲明它,或者以編程方式將其放置在布局中,在第二個活動中為新TextView充氣。
解決了這個問題的部分原因是將接收String變量設置為null
如下所示:
public String param1new = null;
public String param2new= null;
我的問題是我試圖在幾個TextViews
上設置背景顏色,此時只設置第一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.