【发布时间】:2013-04-07 11:59:45
【问题描述】:
我想创建一个关闭当前活动的按钮。就像一个“返回”按钮。 以下是我尝试过的代码片段:
这是完整的.java:
public class OtherApps extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_apps);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.otherappsmenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.previous:
finish();
break;
case R.id.home:
Context context = getApplicationContext();
CharSequence text = "Activitys are not closed!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
break;
case R.id.exit:
finish();
System.exit(0);
case R.id.help:
String url = "http://www.google.de/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
return true;
final Button OtherApps = (Button)findViewById(R.id.previousbutton);
OtherApps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
return true;
}
}
但是 Eclipse 说“第一行无法访问”。 有谁知道错误是什么?
感谢您的帮助!
【问题讨论】:
-
“第一行”——究竟是哪一行?
-
哪个代码无法访问?
-
每个代码的第一行。 "按钮按钮 = (Button) findViewById(R.id.previousbutton);"和“ final Button OtherApps = (Button)findViewById(R.id.previousbutton);”
-
您尝试在
onOptionsItemSelected底部添加previousButton处理程序,在switch块和return之后。尝试将其移至onCreate方法。 -
@YouDeveloper 我已经为您修复了代码缩进。现在问题应该很明显了。
标签: android button android-activity