2011-08-26 58 views
1

我有机器人活动:configChanges =“方向| keyboardHidden”的方向性变化的ImageView更改图像不起作用

我想当设备方向变化在于改变ImageView的图像:

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 

    // refresh the instructions image 
    ImageView instructions = (ImageView) findViewById(R.id.img_instructions); 
    instructions.setImageResource(R.drawable.img_instructions); 
} 

这只适用于手机第一次旋转但不在此之后。

有人可以告诉我为什么会发生这种情况?

回答

1

我认为你试图做这样的事情

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 

    // refresh the instructions image 
    ImageView instructions = (ImageView) findViewById(R.id.img_instructions); 

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 
     instructions.setImageResource(R.drawable.img_instructions_land); 
    } else { 
     instructions.setImageResource(R.drawable.img_instructions_port); 
    } 
} 
1

利用这一点,你可以在多个时间变化的方向是更多的信息转到做工精细

public class VersionActivity extends Activity { 

    ImageView img; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     img = (ImageView) findViewById(R.id.imageView1); 


    } 
    public void onConfigurationChanged(Configuration newConfig) { 
     super.onConfigurationChanged(newConfig); 

     // Checks the orientation of the screen 
     if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { 

      img.setImageResource(R.drawable.splash); 

     } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){ 

      img.setImageResource(R.drawable.icon); 
     } 
     } 

} 

How to detect orientation change in layout in Android?

1

谢谢,既如果我为纵向和横向使用不同的图像名称,答案是正确的并且可行。

要使用这个作品相同的名称:

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 

    // refresh the instructions image 
    ImageView instructions = (ImageView) findViewById(R.id.instructions); 
    // prevent caching 
    try { 
     instructions.setImageResource(0); 
    } catch (Throwable e) { 
     // ignore 
    } 
    instructions.setImageResource(R.drawable.img_instructions); 
    } 
2

Peceps自己的答案IMO是正确的之一,因为它不依赖于绘项目给予不同的名称。看起来资源ID被缓存但drawable不是,所以我们可以将drawable提供给ImageView而不是资源ID,使得该解决方案更加优雅(避免try/catch块):

public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 

    // refresh the instructions image 
    ImageView instructions = (ImageView) findViewById(R.id.instructions); 
    instructions.setImageDrawable(
     getResources().getDrawable(R.drawable.img_instructions)); 

}