gpt4 book ai didi

android - android 中的设备方向缺少动态添加的图像?

转载 作者:行者123 更新时间:2023-11-29 02:04:36 24 4
gpt4 key购买 nike

下面的代码是动态创建 ImageView 并通过单击按钮添加到其父布局。这很好用。当我改变设备方向时,一切都消失了。即,添加图像后,如果我更改设备方向,添加的图像将丢失。为什么?我怎样才能在更改设备方向后取回我的图像?

 @Override
public void onClick(View v) {
//create an imageview
ImageView img = new ImageView(getApplicationContext());

//set layout parameters
img.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

//set image source
img.setImageResource(R.drawable.back);

//add imageview to parent layout
parentView.addView(img);

}

最佳答案

你可以通过这些方式来处理它

1 - onSaveInstanceState() 回调

例如:Saving Android Activity state using Save Instance State http://android-er.blogspot.in/2011/09/onsaveinstancestate-and.html

2- onRetainNonConfigurationInstance() 和 getLastNonConfigurationInstance()

例如:getLastNonConfigurationInstance()

3 - android:configChanges in manifest 和 orverding onConfigChange in activity 例如:http://developer.android.com/resources/articles/faster-screen-orientation-change.html Activity restart on rotation Android

http://developer.android.com/guide/topics/resources/runtime-changes.html

根据您的需要选择一种方式...

关于android - android 中的设备方向缺少动态添加的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com