0

我想创建一个按钮,用于关闭当前活动。就像一个“返回”按钮。以下是我尝试过的代码片段:

这是完整的.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 说“第一行无法访问”。有谁知道错误是什么?

感谢帮助!

4

2 回答 2

2

如果您的“第一行”无法访问,那么更重要的是要知道这两个版本之前的代码是什么。可能是,您在return那里有一个语句或一个总是 的条件false

在这种情况下,将永远无法访问附加单击侦听器的代码。

ps

您有两行从方法返回,这意味着以下代码永远不会执行:

switch(item.getItemId()) {  
   ...
   default: // here, return if none of the values above matched
     return super.onOptionsItemSelected(item); 
}
return true; // here, return always

// conclusion: this gets never executed: Eclipse says "line not reachable"
final Button OtherApps = (Button ...
于 2013-04-07T12:14:29.330 回答
1

该代码应该可以工作(应该首选第一个示例)。

return在粘贴代码之前,您收到的错误听起来好像您在该方法中的任何地方都有- 语句。搜索它,它应该修复错误。

编辑:

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);

        final Button OtherApps = (Button) findViewById(R.id.previousbutton);
        OtherApps.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
            }
        });
}
于 2013-04-07T12:07:01.850 回答