当前位置:编程学习 > wap >>

安卓背景图设置

请问在activity的android:background属性能不能设置为外部存储的图片,比如SD卡上的,android:background="/mnt/sdcard/Image/Main/main_bg.bmp",我是在activity的layout中的FrameLayout设置的。好像运行的时候会报错,找不到文件。我再代码里面可以打开这个文件,证明路径是对的。但是android貌似不认,难道只能添加到res里面,再作为背景吗? 背景图 --------------------编程问答-------------------- 需要通过Bitmap 去加载 --------------------编程问答--------------------
引用 1 楼 zhouzhangkui 的回复:
需要通过Bitmap 去加载


 你是说在代码里面手工加载,然后设置? --------------------编程问答-------------------- 是的,通过代码去加载 --------------------编程问答-------------------- 我知道通过代码可以加载和设置,但是我想直接在xml文件里面配置。这个能不能实现,就是不想自己再写多余的代码。 --------------------编程问答--------------------
引用 4 楼 qwqwqw408 的回复:
我知道通过代码可以加载和设置,但是我想直接在xml文件里面配置。这个能不能实现,就是不想自己再写多余的代码。

这不行吧,万一SD卡的图片删了,那不是要报错啊。 --------------------编程问答--------------------
引用 5 楼 detective2005 的回复:
Quote: 引用 4 楼 qwqwqw408 的回复:

我知道通过代码可以加载和设置,但是我想直接在xml文件里面配置。这个能不能实现,就是不想自己再写多余的代码。

这不行吧,万一SD卡的图片删了,那不是要报错啊。


这个我可以保证会有图片存在,我是问有图片的情况下能不能做到。 --------------------编程问答-------------------- 1.取SD卡图片显示相关的代码:
background.java:

package com.amaker.Sprite;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

@SuppressWarnings("serial")
public class BackGroundActivity extends Activity implements ViewFactory,OnItemSelectedListener,OnTouchListener,OnGestureListener,Serializable{
/*共享数据类*/
    private ClassShared shared;
    SharedPreferences preferences;
SharedPreferences.Editor editor;
private static final String TAG = "BackGroundActivity";
/*webservice测试*/
private Button btnWebServiceTest;
private TextView txtResultOfWebService;
private SoapObject detail;

/*布局成员*/
private RelativeLayout layout_left;  
private LinearLayout layout_right;
private ImageButton btnChangeMode;
private TextView mtextView;
private ImageButton btnChangeBackGround;
private ImageButton btnIntnetSearch;
private RelativeLayout bglayout;
private Gallery g;
private LyricView lyricView;
private ViewTreeObserver viewTreeObserver_left;
private ViewTreeObserver viewTreeObserver_right;
  
@Override
protected void onCreate(Bundle savedInstanceState){
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.background);
/*初始化布局*/
InitLayout();
/*设置事件监听*/
          }

public void InitLayout(){
/*获取布局ID*/
btnWebServiceTest = (Button) findViewById(R.id.btnWebServiceTest);
txtResultOfWebService = (TextView)findViewById(R.id.txtOfWebService);
layout_right = (LinearLayout) findViewById(R.id.layout_right);
layout_left = (RelativeLayout) findViewById(R.id.layout_left);  
    bglayout = (RelativeLayout)findViewById(R.id.backgroundlayout);
    btnChangeBackGround = (ImageButton)findViewById(R.id.btnChangeBackGround);
btnIntnetSearch = (ImageButton)findViewById(R.id.btnIntnetSearch);
    lyricView = (LyricView)findViewById(R.id.mylrc);
    btnChangeMode = (ImageButton)findViewById(R.id.btnChangeMode);
mtextView = (TextView)findViewById(R.id.textViewMode);
g = (Gallery) findViewById(R.id.gallery);
//显示布局
/*设置可监听触摸手势的控件*/
mGestureDetector=new GestureDetector(this);
    layout_left.setOnTouchListener(this);  
    layout_right.setOnTouchListener(this);
    lyricView.setOnTouchListener(this);
lyricView.setLongClickable(true);
bglayout.setOnTouchListener(this);
bglayout.setLongClickable(true);
/*初始化共享数据类*/
shared = (ClassShared)getApplication();
/*preferences设置播放模式*/
Context ctx = BackGroundActivity.this;
preferences = ctx.getSharedPreferences("11",MODE_WORLD_READABLE);/*获取只能被本程序读写的sharedpreferences对象*/
editor = preferences.edit();/*获取修改器*/
String backgroundId = preferences.getString("backgroundId", "");
if(backgroundId.equals("")){
layout_left.setBackgroundResource(R.drawable.pic8);
}
else{
try {
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,backgroundId+"");
Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
layout_left.setBackgroundDrawable(new BitmapDrawable(bm));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String modeText = preferences.getString("modeType","列表循环ing");
mtextView.setText(modeText);
}


    btnChangeBackGround.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Log.i(TAG,"换背景 -----");

shared.GetPicture();
SetGallary();
}
    });
    

@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub

}

    //layout_right
    @Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,shared.mPicList.get(arg2).get("PicId")+"");
try {
Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
layout_left.setBackgroundDrawable(new BitmapDrawable(bm));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
editor.putString("backgroundId",shared.mPicList.get(arg2).get("PicId").toString());
editor.commit();
}
    public void SetGallary()
{
g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
        g.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
        });
}

    public class ImageAdapter extends BaseAdapter{
private Context mContext;
     public ImageAdapter(Context c){
     mContext = c;
     }
     public int getCount(){
     //Log.i(TAG,"----mPicList.size() ="+Integer.toString(mPicList.size()));
     return shared.mPicList.size();
     }
     public Object getItem(int position)
     {
     return position;
     }
     public long getItemId(int position)
     {
     return position;
     }
     public View getView(int position,View convertView,ViewGroup parent){
     ImageView i = new ImageView(mContext);
     Uri uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,shared.mPicList.get(position).get("PicId")+"");
     Bitmap bm;
try {
bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
i.setImageBitmap(bm);
i.setAdjustViewBounds(true);
     i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
     i.setScaleType(ImageView.ScaleType.FIT_CENTER);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
     return i;
     }
    }
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView i = new ImageView(this);
     i.setScaleType(ImageView.ScaleType.FIT_CENTER);
     i.setLayoutParams(new ImageSwitcher.LayoutParams(
     LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
     return i;
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
}






2.background.xml文件,只保留了图片读取相关的控件:

<?xml version="1.0" encoding="utf-8" ?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/backgroundlayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
  <ImageButton android:id="@+id/btnChangeBackGround" android:layout_below="@+id/btnChangeMode" android:layout_alignParentLeft="true" android:src="@drawable/rest" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 
    <Gallery android:id="@+id/gallery"
       android:background="#55000000"
       android:layout_width="fill_parent"
       android:layout_alignParentBottom="true"
       android:layout_height="60dip"
       android:spacing="16dp"
       android:gravity="center_vertical"
   /> 
 </RelativeLayout>


这是我程序里面弄出来的,有这些代码应该可以写出来了。希望有用。 --------------------编程问答-------------------- InitLayout()里面的可以不看,有些东西没删干净,主要是
1.先让BackGroundActivity类implements相应的接口
2.实现接口相应的函数。
需要的接口我都已经保留下来了。 --------------------编程问答-------------------- 从MediaStore中读取图片,不会有不同步的问题。
还忘了给你一个函数了:
先是存储图片的链表:

//图片库,用于存储图片
public List<HashMap<String,Object>> mPicList = new ArrayList<HashMap<String,Object>>();

然后是从SD卡读取图片的函数:

public void GetPicture(){
Cursor cursor=null;
try{
cursor = this.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, null, null, null,null);
cursor.moveToFirst();
String  picUrl=null;//路径
String picName=null;//标题
int picId = 0;//ID
while(cursor!=null&&cursor.moveToNext())
{
picUrl= cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
picId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("PicUrl",picUrl);
map.put("PicId",picId);
mPicList.add(map);
}
}finally{
if(cursor!=null){
try{
cursor.close();
}catch(Exception e){

}
}
}
}


不能再详细了。 --------------------编程问答-------------------- 除 --------------------编程问答-------------------- 除 --------------------编程问答-------------------- 通过Bitmap 去加载 --------------------编程问答--------------------
补充:移动开发 ,  Android
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,