我要做的是创建一个非常简单的应用程序,显示“欢迎使用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);*/
}
}
}
}
答案 0 :(得分:0)
试试这个
if(btn.getId()==v.getId())
答案 1 :(得分:0)
感谢您的协助。几个小时后,我想我必须使用setTitle()。