方向更改后设置 imageview

Set imageview after orientation change

我有以下代码,在我旋转我的 phone 之前它工作得很好。然后我必须再次单击以加载图像,我知道当我们旋转 activity 重新启动时,我们有一些方法来存储状态并恢复它,但在我的情况下,您可以看到 img 文件是在一个字符串中,因为它是随机生成的。 那么如何利用onConfigurationChanged(貌似很容易理解)恢复旋转前的图像呢?

public class HomeScreen extends Activity {

    protected ImageView imgView;
    protected String str;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);
        final Random rnd = new Random();
        ActionBar actionBar = getActionBar();
        actionBar.hide();

        imgView = (ImageView) findViewById(R.id.imgRandom);

        if (savedInstanceState != null) {
            str = savedInstanceState.getString("param");
            imgView.setImageDrawable
                    (
                            getResources().getDrawable(getResourceID(str, "drawable", getApplicationContext()))
                    );




            imgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {



                   // final ImageView img = (ImageView) findViewById(R.id.imgRandom);
                    // I have 3 images named img_0 to img_2, so...
                    str = "img" + rnd.nextInt(9);
                    imgView.setImageDrawable
                            (
                                    getResources().getDrawable(getResourceID(str, "drawable", getApplicationContext())));


                }


            });


        }
    }

    protected void onSaveInstanceState(Bundle savedInstanceStat) {
        super.onSaveInstanceState(savedInstanceStat);
        savedInstanceStat.putString("param", str);
    }

当我旋转它时它崩溃了,而且在加载时或者点击时没有图像正在加载..

> 07-07 21:11:32.950: I/InputReader(468): Device reconfigured: id=1,
> name='Genymotion Virtual Input', size 1080x1920, orientation 0, mode
> 1, display id 0 07-07 21:11:32.950: I/ActivityManager(468): Config
> changes=480 {1.0 310mcc260mnc en_US ?layoutDir sw360dp w360dp h567dp
> 480dpi nrml port finger qwerty/v/v dpad/v s.14} 07-07 21:11:33.081:
> W/ResourceType(1861): Too many attribute references, stopped at:
> 0x01010034 07-07 21:11:33.081: W/ResourceType(1861): Too many
> attribute references, stopped at: 0x01010034 07-07 21:11:33.082:
> D/AndroidRuntime(1861): Shutting down VM 07-07 21:11:33.083:
> E/AndroidRuntime(1861): FATAL EXCEPTION: main 07-07 21:11:33.083:
> E/AndroidRuntime(1861): Process:
> app.motivation.techiequickie.ypb.motivation, PID: 1861 07-07
> 21:11:33.083: E/AndroidRuntime(1861): java.lang.RuntimeException:
> Unable to start activity
> ComponentInfo{app.motivation.techiequickie.ypb.motivation/app.motivation.techiequickie.ypb.motivation.HomeScreen}:
> java.lang.NullPointerException: name is null 07-07 21:11:33.083:
> E/AndroidRuntime(1861):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.app.ActivityThread.access0(ActivityThread.java:151) 07-07
> 21:11:33.083: E/AndroidRuntime(1861):     at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.os.Handler.dispatchMessage(Handler.java:102) 07-07
> 21:11:33.083: E/AndroidRuntime(1861):     at
> android.os.Looper.loop(Looper.java:135) 07-07 21:11:33.083:
> E/AndroidRuntime(1861):   at
> android.app.ActivityThread.main(ActivityThread.java:5254) 07-07
> 21:11:33.083: E/AndroidRuntime(1861):     at
> java.lang.reflect.Method.invoke(Native Method) 07-07 21:11:33.083:
> E/AndroidRuntime(1861):   at
> java.lang.reflect.Method.invoke(Method.java:372) 07-07 21:11:33.083:
> E/AndroidRuntime(1861):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 07-07
> 21:11:33.083: E/AndroidRuntime(1861): Caused by:
> java.lang.NullPointerException: name is null 07-07 21:11:33.083:
> E/AndroidRuntime(1861):   at
> android.content.res.Resources.getIdentifier(Resources.java:2034) 07-07
> 21:11:33.083: E/AndroidRuntime(1861):     at
> app.motivation.techiequickie.ypb.motivation.HomeScreen.getResourceID(HomeScreen.java:148)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> app.motivation.techiequickie.ypb.motivation.HomeScreen.onCreate(HomeScreen.java:35)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.app.Activity.performCreate(Activity.java:5990) 07-07
> 21:11:33.083: E/AndroidRuntime(1861):     at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
> 07-07 21:11:33.083: E/AndroidRuntime(1861):   ... 11 more 07-07
> 21:11:33.084: W/ActivityManager(468):   Force finishing activity 1
> app.motivation.techiequickie.ypb.motivation/.HomeScreen
  1. 创建两个class级变量来存储当前随机数和存储图像状态例如:- IsImageDownloaded(布尔)
  2. 覆盖OnInstanceSave()方法并捕获当前随机数和图像状态。
  3. (当您旋转设备时,将再次调用 onCreate())在 onCreate() 中检查 isImageDownloaded 是真还是假(如果条件)。如果为真,则获取捕获的随机数并使用此随机数再次显示图像。
  4. 您可以创建一个单独的方法来加载特定随机数的图像,您可以在 onClick() 方法和 if 条件中使用此方法。

看来主要问题是您对 imgView.setOnClickListener() 的调用嵌套在 if (savedInstanceState != null) 案例中。

我通过取消嵌套点击侦听器并在要查找的资源名称中添加下划线使您的代码正常工作。我使用了九张图片,命名为 img_0.pngimg_8.png,然后放在 drawable 文件夹中。

我还添加了在启动时加载随机图像的代码。

之后,它在点击时成功加载了另一个随机图像。我还测试了屏幕旋转,您现有的代码工作正常,无论我旋转屏幕多少次,它都保持当前图像存在。

这是完整的工作和测试代码:

public class HomeScreen extends Activity {

    protected ImageView imgView;
    protected String str;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_screen);
        final Random rnd = new Random();
        //ActionBar actionBar = getActionBar();
        //actionBar.hide();

        imgView = (ImageView) findViewById(R.id.imgRandom);


        if (savedInstanceState != null) {
            str = savedInstanceState.getString("param");
            Log.d("image screen rotation", str);
            imgView.setImageDrawable
                    (
                            getResources()
                            .getDrawable(getResourceID(str, "drawable", getApplicationContext()))
                    );
        }
        else{
            str = "img_" + rnd.nextInt(9);
            Log.d("image startup", str);
            imgView.setImageDrawable(
                    getResources()
                            .getDrawable(getResourceID(str, "drawable", getApplicationContext())));
        }

        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                // final ImageView img = (ImageView) findViewById(R.id.imgRandom);
                // I have 3 images named img_0 to img_2, so...
                str = "img_" + rnd.nextInt(9);
                Log.d("image click", str);
                imgView.setImageDrawable(
                         getResources()
                         .getDrawable(getResourceID(str, "drawable", getApplicationContext())));

            }
        });


    }

    protected final static int getResourceID
            (final String resName, final String resType, final Context ctx)
    {
        final int ResourceID =
                ctx.getResources().getIdentifier(resName, resType,
                        ctx.getApplicationInfo().packageName);
        if (ResourceID == 0)
        {
            throw new IllegalArgumentException
                    (
                            "No resource string found with name " + resName
                    );
        }
        else
        {
            return ResourceID;
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle savedInstanceStat) {
        super.onSaveInstanceState(savedInstanceStat);
        savedInstanceStat.putString("param", str);
    }
}

来自 运行 应用程序的结果日志,点击 ImageView 更改图像,然后旋转屏幕:

 D/image startup﹕ img_8
 D/image screen rotation﹕ img_8
 D/image screen rotation﹕ img_8
 D/image click﹕ img_3
 D/image screen rotation﹕ img_3
 D/image screen rotation﹕ img_3
 D/image screen rotation﹕ img_3
 D/image screen rotation﹕ img_3
 D/image click﹕ img_7
 D/image screen rotation﹕ img_7
 D/image screen rotation﹕ img_7
 D/image screen rotation﹕ img_7
 D/image screen rotation﹕ img_7
 D/image screen rotation﹕ img_7
 D/image screen rotation﹕ img_7

在您的清单中使用它。

    <activity
        android:name="youractivity"
        android:configChanges="keyboardHidden|screenSize|orientation" >
    </activity>

这将自行处理方向更改。并删除 savedInstance 编码

简单地说,您可以先将图像存储在本地,然后获取该图像并在旋转时间或其他时间进行设置。这也会增加您的应用程序加载图像的时间