方向改变后设置imageview

时间:2015-07-05 08:04:38

标签: android rotation imageview

我有以下代码,直到我旋转手机才能正常工作。然后我必须再次单击以加载图像,我知道当我们旋转活动重新启动时,我们有一些方法来存储状态并恢复它,但在我的情况下,你可以看到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);
    }

当我旋转时,它会崩溃并且在加载时或onClick没有图像正在加载..

> 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.access$900(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

4 个答案:

答案 0 :(得分:5)

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

我通过取消嵌套点击侦听器并在资源名称中添加下划线来查找代码。我使用了9个图像,名为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

答案 1 :(得分:2)

  1. 创建两个类级变量来存储当前随机数并存储图像状态,例如: - IsImageDownloaded(布尔值)
  2. 覆盖OnInstanceSave()方法并捕获当前的随机数和图像状态。
  3. (当您旋转设备时,将再次调用onCreate())在onCreate()中检查isImageDownloaded是真还是假(如果条件)。如果是,则获取捕获的随机数并使用此随机数再次显示图像。
  4. 您可以创建一个单独的方法来加载特定随机数的图像,您可以在onClick()方法和if条件中使用此方法。

答案 2 :(得分:1)

在清单中使用此功能。

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

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

答案 3 :(得分:0)

只需先将图像存储在本地,然后只需获取此图像并设置为旋转时间。这也会增加负载图像的应用时间