无法在Actionbar中实现后退按钮

时间:2014-06-18 15:14:30

标签: android android-actionbar

我正在使用ActionBar创建一个应用程序。 在哪个操作栏执行共享操作。 但我想添加后退按钮以及共享实现。 基本上我希望根据用户选择来完成两件事。

这是我的代码:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }

        // Handle item selection
        ImageView image = (ImageView) findViewById(R.id.full_image_view); //Unreachable Code
        Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

        File sd = Environment.getExternalStorageDirectory();
        String fileName = "desi.png";
        File dest = new File(sd, fileName);
        try {
            FileOutputStream out;
            out = new FileOutputStream(dest);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch (item.getItemId()) {
            case R.id.item:
                Uri uri = Uri.fromFile(dest);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                shareIntent.setType("image/*");
                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

我自己实现了这两件事,但结果是eclipse提到的无法访问的代码。 任何帮助将不胜感激。 谢谢!

1 个答案:

答案 0 :(得分:2)

这是正确的代码:

switch (item.getItemId()) {
            case R.id.item:
                Uri uri = Uri.fromFile(dest);
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
                shareIntent.setType("image/*");
                startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.share)));
                return true;


            case android.R.id.home:
                // app icon in action bar clicked; go home
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

我尝试在单个switch语句中实现这两种情况,这样就消除了错误,并且应用程序正在根据代码运行。 谢谢!

相关问题