我正在尝试使此处的位图图片显示在方向更改后的ImageView中,而不是从可绘制文件夹中获取的图片。
我知道saveInstance可以做到这一点,但是不确定如何使用它。
我也尝试过onCofigureationChange(),但是没有运气。

public class MainActivity extends AppCompatActivity {

static final int REQUEST_IMAGE_CAPTURE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

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

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        imageView.setImageBitmap(imageBitmap);
    }
}

public void taBilde(View view) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}
}

最佳答案

要获取生命周期更改中的数据,可以使用this link中的ViewModel

更新

我在kotlin中为此解决方案编写了代码。您可以用Java编写它。

import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import android.graphics.Bitmap


/**
 * Created by Amin on 9/6/2018.
 */
class ThumbnailHolderViewModel : ViewModel() {

    private var thumbnail: MutableLiveData<Bitmap>? = null

    fun setThumbnail(bitmap: Bitmap) {
        if (thumbnail == null) {
            thumbnail = MutableLiveData()
        }
        thumbnail?.value = bitmap
    }

    fun getThumbnail(): LiveData<Bitmap>? {
        return thumbnail
    }

}


在您的活动中初始化ViewModel:

val viewModel = ViewModelProviders.of(this).get(ThumbnailHolderViewModel::class.java)
viewModel.setThumbnail(yourThumbnailBitmap)


并从中获取保留的数据:

val viewModel = ViewModelProviders.of(this).get(ThumbnailHolderViewModel::class.java)
viewModel.getThumbnail()?.observe(this, Observer<Bitmap?> { bitmap ->
    if (bitmap != null) {
        // do sth...
    }
})

10-08 03:18