我要做的是创建一个非常简单的应用程序,显示“欢迎使用 Android,[NAME]!” 作为文本字段和应用程序的标题。但是,我希望应用程序仅在按下按钮后才显示此内容,如果用户将该字段留空,则显示“欢迎使用 Android”。我设法让按钮和文本正确显示,而不是标题。我试过在网上寻找答案,但只遇到了一种使用 string.xml 的方法。如何编写 java 代码来更改应用程序的标题?
这是我到目前为止所拥有的:
package com.helloandroidbutton;
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
/**Called when activity is created. */
private Button btn;
private EditText edit;
private TextView view;
private RelativeLayout title;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText)findViewById(R.id.editText1);
view = (TextView)findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
title = (RelativeLayout)findViewById(R.string.app_name);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
if(btn==v){
if(edit.getText().toString().equals("")){
String msg ="Welcome to Android!";
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
view.setText(msg);
//This was my attempt to change the title
/*title.setText(msg);*/
}
else{
String msg ="Welcome to Android, " + edit.getText() + "!";
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
view.setText(msg);
/*title.setText(msg);*/
}
}
}
}