8

我已经完全重写了这个问题,以缩小范围。

我有两个像卡片一样翻转的碎片(左,右)。当前面的片段消失时,它会翻转它显示后面。再次单击按钮后,它会再次翻转到前面,但前面片段上的 ImageView 消失了。

我尝试了不同的方法来保存所选图像的数据。

  1. 保存片段 onSaveInstanceState

这给了我一个空指针,所以我想我需要一些更恒定的东西。

  1. 所以现在我将图像保存到 SDCard 一次选择

我认为这会起作用,只需检查路径并在它翻转到前面或重新创建活动时抓住它。

这是一些代码

创建():

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_postcard_activity);
        //UI call
        frontImageView = (ImageView) findViewById(R.id.imageView);
        Log.d(tag, "onCreate() Instance:" + savedInstanceState);
        //fragment start
          if (savedInstanceState == null) {
              Log.d(tag,"Instance Null");
                getFragmentManager()
                        .beginTransaction()
                        .add(R.id.postcardFrame, new CardFrontFragment())
                        .commit();
                if(!mShowingBack){
                    Log.d(tag,"Not showing back");
                    if(newPath != null && newPath != ""){
                        Log.d(tag, "entered new path, not empty");
                        Drawable drawable = Drawable.createFromPath(newPath);
                        Log.d(tag, "Should be setting saved image.");
                        frontImageView.setImageDrawable(drawable);
                    }
                  }  
            } 
          else 
          {
                mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
                Log.d(tag, "Instance is not Null");
          }

翻转按钮单击侦听器

//flip card
final Button cardBackButton = (Button) findViewById(R.id.cardBackButton);
cardBackButton.setOnClickListener(new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        flipCard();
});

翻牌法:

private void flipCard()
    {
        Log.d(tag2, "Log after flipCard:" + mShowingBack);
        if(mShowingBack)
        {
            //Flip to front
            flipFront();
             return;
        }
        // Flip to back
        flipBack();
    }

我从他们的 PhotoGallery 设置了图像 onActivityResult

protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);

        if (resultCode == RESULT_OK) {
            Uri photoUri = intent.getData();

            if (photoUri != null) {
                try {
                    ImageView setImage = (ImageView)findViewById(R.id.imageView);
                    frontImage = MediaStore.Images.Media.getBitmap(this
                        .getContentResolver(), photoUri);
                    imageSet = true;
                    //save image to SD
                    if(imageSet == true){
                        Log.d(tag, "Inside Image Set if Statement");
                    String path = getExternalCacheDir() + "Postcards.png";
                    if(path != null && path != ""){
                    Log.d(tag, "Path is:" + path);
                    File file = new File(path);
                    newPath = file.getAbsolutePath();
                    Log.d(tag, "New Path:" + newPath);
                    if(file.exists()){
                        Log.d(tag, "File Exists");
                        Drawable d = Drawable.createFromPath(newPath);
                        setImage.setImageDrawable(d);

                    }else{
                        try{
                            Log.d(tag,"File didnt exist");
                            FileOutputStream out = new FileOutputStream(file);
                            frontImage.compress(Bitmap.CompressFormat.PNG, 90, out);
                            if(file.exists()){
                                Log.d(tag, "file exists now");
                            newPath = file.getAbsolutePath();
                            Drawable b = Drawable.createFromPath(newPath);
                            setImage.setImageDrawable(b);
                            }
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

这就是我访问图像并尝试在 Restart() 上将其设置为我的 ImageView 的方式

if(imageSet == true){
            if(newPath != null && newPath != ""){
                ImageView view = (ImageView) findViewById(R.id.imageView);
                Drawable drawable = Drawable.createFromPath(newPath);
                view.setImageDrawable(drawable);
            }
        }

这似乎是获取图像和设置图像的最佳途径,但它不起作用。什么是最佳实践,我怎样才能让它按照我需要的方式执行?

非常感谢任何帮助!

4

1 回答 1

3

savedInstanceState服务于不同的目的。

onSaveInstanceState (Bundle):在一个活动可能被杀死之前调用这个方法,这样当它在未来某个时间回来时,它可以恢复它的状态

而且,在您的特定情况下,甚至可能不需要它。单击按钮时,您正在更改片段,而不是重新启动您的应用程序。

据我所知,您让用户创建一张明信片:一面是图片(比如 A 面),另一面是一条消息(比如 B 面)。当应用程序启动时,A 面就在视图中。以某种方式,您让用户从图库中选择图像。我会假设它onActivityResult(int, int, Intent)按预期工作,并将图像设置为 ImageView - R.id.imageView。单击按钮时,视图变为 B 面。再次单击按钮时,视图变为 A 面,但用户选择的图像不存在。

您可以在里面做的一件事onActivityResult(int, int, Intent)是:将图像的路径保存在 SharedPreferences 中。

SharedPreferences preferences;
final String PREFS = "your.application.name.prefs";

// Keyword to find the path
final String IMAGE_SELECTED_BY_USER = "image_selected_by_user";

// Use a default image when the user starts the app for the first time
// or if the retrieved path points to a deleted image etc.
final String PATH_TO_A_DEFAULT_IMAGE = "path_to_a_default_image"    

@Override
protected void onCreate(Bundle savedInstanceState) {

    ....
    ....
    preferences = getActivity().getSharedPreferences(PREFS, 0);
    imagePath = preferences.getString(IMAGE_SELECTED_BY_USER, PATH_TO_A_DEFAULT_IMAGE);

    frontImageView = (ImageView) findViewById(R.id.imageView);

    Drawable drawable = null;

    if (new File(imagePath).exists()) {
        drawable = Drawable.createFromPath(imagePath);
    } else {
        drawable = Drawable.createFromPath(PATH_TO_A_DEFAULT_IMAGE);
    }

    frontImageView.setImageDrawable(drawable);

    getFragmentManager()
        .beginTransaction()
        .add(R.id.postcardFrame, new CardFrontFragment())
        .commit();

    ....
    ....
}

onActivityResult(int, int, Intent),保存图片路径:

if(file.exists()){
    Log.d(tag, "File Exists");
    Drawable d = Drawable.createFromPath(newPath);
    setImage.setImageDrawable(d);

    Editor editor = preferences.edit();
    editor.putString(IMAGE_SELECTED_BY_USER, newPath);
    editor.commit();
} else{
    try{
        Log.d(tag,"File didnt exist");
        FileOutputStream out = new FileOutputStream(file);
        frontImage.compress(Bitmap.CompressFormat.PNG, 90, out);
        if (file.exists()) { 
            Log.d(tag, "file exists now");
            newPath = file.getAbsolutePath();
            Drawable b = Drawable.createFromPath(newPath);
            setImage.setImageDrawable(b);

            Editor editor = preferences.edit();
            editor.putString(IMAGE_SELECTED_BY_USER, newPath);
            editor.commit();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这样,当用户启动应用程序时,他/她将看到默认图像或先前选择的图像。

哪里savedInstanceState有用:假设您给用户一个在 B 面写短消息的选项。现在,如果在写消息时,用户将设备从横向旋转到纵向(反之亦然),他/她写的将消失,因为活动将被销毁并重新创建。要保存消息,您将使用onSaveInstanceState(Bundle)

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString("Text_To_Save", someEditText.getText().toString());
}

轮换时,活动的onCreate(Bundle)' will be called. The bundle passed is the same one fromonSaveInstanceState(Bundle)`。要检索文本:

String savedString = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        if (savedInstanceState.contains("Text_To_Save")) {
            savedString = savedInstanceState.getString("Text_To_Save");
        }
    }

    someEditText.setText(savedString);
}  
于 2013-08-12T08:01:15.063 回答