我目前正在自学Android编程,所以请用初学者可以理解的方式解释你的答案。
我试图编辑文本在TextView对象使用公共静态字符串对象从其他屏幕/活动。有两个公共静态字符串对象,分别称为crew_id和orderType(两者都初始化为空字符串)。在Activity中有一个名为NewOrderActivity的TextView对象,其id为"crew_id_and_ordertype"。
我的NewOrderActivity.class的代码目前是这样的:
按钮启动NewOrderActivity的代码是:
public void goToNewOrder(View view)
{
final EditText edit = (EditText) findViewById(R.id.editText1); //gets the string from the EditText object
crew_id = edit.getText().toString();
Intent k = new Intent(CrewIDActivity.this, NewOrderActivity.class);
startActivity(k);
}
NewOrderActivity的代码是:
public class NewOrderActivity
extends Activity{
TextView info = (TextView)findViewById(R.id.crew_id_and_ordertype);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
info.setText("Crew ID: " + CrewIDActivity.crew_id + "/n /n" + OrderingActivity.orderType);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_order, menu);
return true;
}
当我尝试从以前的活动转到NewOrderActivity时,应用程序停止工作。我做错了什么?这是一个问题,我如何尝试编辑TextView对象,还是别的什么?
除非设置了视图,否则无法初始化组件。TextView信息行代码应该放在setContentView
public class NewOrderActivity
extends Activity{
TextView info = (TextView)findViewById(R.id.crew_id_and_ordertype);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
info.setText("Crew ID: " + CrewIDActivity.crew_id + "/n /n" + OrderingActivity.orderType);
}
改成:
public class NewOrderActivity
extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
TextView info = (TextView)findViewById(R.id.crew_id_and_ordertype);
info.setText("Crew ID: " + CrewIDActivity.crew_id + "/n /n" + OrderingActivity.orderType);
}