Ⅰ android设置背景图片
教你如何设置背景图片
xml文件设置背景图片中:
任意一个控件,button imageView 或layout,在其的xml属性设置中,添加
[java] view plain
android:background="@drawable/bg"
即可实现设置其背景图片为bg.
其中bg.bnp图片存放在drawable目录下。
drawable目录下存放大小图标共用的图片。drawable-hdpi中存放240 WVGA800 的模拟器或板子用的图片。drawable-mdpi存放对应的小图片
[java] view plain
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/pic"/>
同样,用src属性,也可设置imageView的图片为pic.png
java代码中设置或更改一个控件的背景图片:
[java] view plain
Resources resources = getContext().getResources();
Drawable btnDrawable = resources.getDrawable(R.drawable.layout_bg);
layout.setBackgroundDrawable(btnDrawable);
程序中,动态修改layout的背景图片,用setBackgroundDrawable()函数实现。设置其背景图片为 layout_bg.png
修改imageView1的背景图片为imageView2的背景图片:
imageView2.getDrawable()可获得图片2的背景。值为Drawable类型
imageView1.setImageDrawable(drawable); 设置imageView1的背景图片
即:
[java] view plain
imageView1.setImageDrawable(imageView2.getDrawable());
Ⅱ android中怎么实现动态设置背景图片的功能,我在网上搜到的只能设置到当前的页面,并不能实现设置到全部
当关闭重新运行,它又会自动跳回原始的背景图片。
在开发过程中,由于使用模拟器测试了程序,在首次运行后会将res文件夹下的图片资源文件(如drawable-hdpi、drawable-ldpi和drawable-mdpi)拷贝到bin文件夹下。在替换资源图片后,eclipse并不清楚是否有图片改变,所以会使用原来bin下的res文件夹中的资源文件进行打包,而图片用的还是第一次eclipse所拷贝进去的文件,所以当运行程序后会发现替换资源图片在程序中没起作用。
解决办法:每次运行前,清理项目
动态设置背景图片代码
privateinti=0;//全局变量定义,初始化
//list数组接收到从文件中读取到的数据
List<String>list=readTxt.getDierguanResource();
//changeBack这个函数用来动态设置背景图片
publicvoidchangeBack(intbackground){
main=(LinearLayout)findViewById(R.id.shizi);
Stringa=list.get(background);
//获取到的背景图片名as(图片存到res/drawable文件下)
Stringas=a.split("")[1];
//动态获取图片getResources().getIdentifier(as,"drawable",getPackageName())
intresID=getResources().getIdentifier(as,"drawable",getPackageName());
//设置页面背景setBackgroundResource()
main.setBackgroundResource(resID);
}
if(i>=0&&i<list.size()){
changeBack(i);
}