Android apk中有时候需要识别场景动态设置背景图片,而不是写死在布局文件中。
这里介绍2中方式动态设置背景图片。
布局文件activity_hello.xml为:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/bg_id" >
android:id="@+id/pic"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
........................
Java代码如下所示:
public class Hello extends Activity { private static RelativeLayout mBgLayout; private static String mBgId; private static final String mBgPicture = "/data/data/com.example.hello/files/bgpicture.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello); mBgLayout = (RelativeLayout) findViewById(R.id.bg_id); //方式一:设置布局背景图片 //资源文件中需要一张xiao.jpg(图片格式即可:.png等),至少要有一张默认图片default.jpg mBgId = "xiao"; int id = getResources().getIdentifier(mBgId, "drawable", getPackageName()); if(id != 0){ layout.setBackgroundDrawable(getResources().getDrawable(id)); }else{ layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.default)); } //方式二:动态加载图片资源覆盖整个布局背景 //mBgPicture可以在应用程序中动态更新,比如定期去服务器下载更新 //这里只负责显示,更新部分未包含在代码中 try{ ImageView picture = (ImageView) findViewById(R.id.pic); int width = mBgLayout.getLayoutParams().width; int height = mBgLayout.getLayoutParams().height; Bitmap bmp = convertToBitmap(mBgPicture, width, height); if(bmp != null){ picture.setImageBitmap(bmp); picture.setScaleType(ImageView.ScaleType.FIT_XY); } }catch (NullPointerException e) { e.printStackTrace(); } } }