«

Android访问图库并将所选图片转换为Drawable并设为背景

时间:2024-3-2 19:51     作者:韩俊     分类: Android


在网上找了一天,大多数是用Intent.ACTION_GET_CONTET来实现,可能是很早的版本了,我在5.0系统中调用进入的是最近使用过的图片页面,而不是全部的图片,选择也出问题,后来改用Intent.ACTION_PICK才得到解决,设置背景也很简单,只要获取layout的id,获取图片绝对路径,用layout.setBackground(Drawable.createFromPath())传入路径即可。拨号和发短信界面同理,还要简单一点。

<strong><span style="font-size:18px;">public class MainActivity extends Activity {
    private Button button=null;
    private LinearLayout layout=null;
    private static final int CHOOSE=0;
    private final String IMAGE_TYPE="image/*";
    <span style="color:#ff6666;">@Override</span>
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        layout=(LinearLayout)findViewById(R.id.layout);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_choose=new Intent(Intent.ACTION_PICK);//Intent.ACTION_GET_CONTENT和是获得最近使用过的图片。
                intent_choose.setType(IMAGE_TYPE);//应该是指定数据类型是图片。
                startActivityForResult(intent_choose,CHOOSE);
            }
        });
    }

    <span style="color:#ff6666;">@Override</span>
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CHOOSE:
                if(resultCode==RESULT_OK){
                    Uri imageUri=data.getData();//图片的相对路径
                    Cursor cursor = getContentResolver().query(imageUri, null, null, null, null);//用ContentProvider查找选中的图片
                    cursor.moveToFirst();
                    String path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));//获取图片的绝对路径
                    File imageFile=new File(path);
                    Drawable drawable=Drawable.createFromPath(path);
                    layout.setBackground(drawable);
                    cursor.close();
                }
                break;
        }
    }
}
<img src="http://img.blog.csdn.net/20150627113559632?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTgxMjgyMzA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<img src="http://img.blog.csdn.net/20150627113615513?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTgxMjgyMzA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<img src="http://img.blog.csdn.net/20150627113627042?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYTgxMjgyMzA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />




        <p>版权声明:本文为博主原创文章,未经博主允许不得转载。</p>

标签: android

热门推荐