片段翻转和损失图像

Kee*_*ano 8 android android-fragments

我已经完全重写了问题,以便缩小范围.

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

我尝试过保存所选图像数据的不同方法.

  1. 保存片段onSaveInstanceState

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

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

这个我认为可行,只需检查路径并抓住它,如果它翻转到前面或重新创建活动.

这是一些代码

的onCreate():

@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");
          }
Run Code Online (Sandbox Code Playgroud)

翻转按钮单击"侦听器"

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

    @Override
    public void onClick(View v) {
        flipCard();
});
Run Code Online (Sandbox Code Playgroud)

flipCard方法:

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

我从他们的PhotoGallery中设置了Image 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();
                }
Run Code Online (Sandbox Code Playgroud)

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

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

这似乎是获取图像和设置图像的最佳途径,但它不起作用.什么是最佳实践,如何让它以我需要的方式执行?

非常感谢任何帮助!

Vik*_*ram 3

savedInstanceState服务于不同的目的。

onSaveInstanceState (Bundle):在 Activity 被终止之前调用此方法,以便当它在未来某个时间返回时可以恢复其状态

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

据我所知,您正在让用户创建一张明信片:一侧是图片(例如 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();

    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

在 中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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

哪里savedInstanceState有用:假设您为用户提供了在 B 面编写短信的选项。现在,如果在编写消息时,用户将设备从横向旋转为纵向(或反之亦然),则该消息/她写道将会消失,因为该活动将被销毁并重新创建。要保存消息,您可以使用onSaveInstanceState(Bundle)

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

    outState.putString("Text_To_Save", someEditText.getText().toString());
}
Run Code Online (Sandbox Code Playgroud)

轮换时,活动的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);
}  
Run Code Online (Sandbox Code Playgroud)