android – 片段翻转和丢失图像

前端之家收集整理的这篇文章主要介绍了android – 片段翻转和丢失图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经完全重写了这个问题,以便缩小范围.

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

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

>保存碎片onSaveInstanceState

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

>所以现在我将图像保存到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");
          }

翻转按钮单击“侦听器”

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

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

flipCard方法

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

我从他们的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();
                }

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

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

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

非常感谢任何帮助!

解决方法

savedInstanceState用于不同的目的.

onSaveInstanceState (Bundle):
This method is called before an activity may be killed so that when it
comes back some time in the future it can restore its state

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

从我所看到的,你让用户创建一张明信片:一面是图片(比如A面),另一面是消息(比如说B面).当应用程序启动时,A侧即可查看.在某种程度上,您让用户从图库中选择一个图像.我将假设onActivityResult(int,int,Intent)按预期工作,并将图像设置为ImageView – R.id.imageView.单击按钮时,视图将更改为B侧.再次单击该按钮时,视图将更改为A面,但用户选择的图像不存在.

你可以在onActivityResult(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,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,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面写短信的选项.现在,如果在写消息时,用户将设备从Landscape旋转到Portrait(反之亦然),那么消息他就是/她写的将会消失,因为活动将被销毁并重新创建.要保存消息,可以使用onSaveInstanceState(Bundle):

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

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

轮换时,将调用活动的onCreate(Bundle)’.传递的包与fromSaveInstanceState(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);
}
原文链接:https://www.f2er.com/android/317948.html

猜你在找的Android相关文章