Android获取指定路径的图片(通过Drawable方式)

本文详细介绍了如何在Android应用中通过指定文件路径来获取图片资源并转化为Drawable对象,包括读取本地文件、设置权限和处理异常等方面的关键步骤。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:textAllCaps="false"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>


package success.xiaoyu.loadimage;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Drawable drawable = (Drawable)msg.obj;
            imageView.setImageDrawable(drawable);

        }
    };
    private ImageView imageView;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        Button button = (Button)findViewById(R.id.button);
       imageView = (ImageView)findViewById(R.id.image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Drawable drawable = loadImage("http://115.159.217.226/xy.jpg");
                        Message msg = new Message();
                        msg.obj = drawable;
                        handler.sendMessage(msg);
                    }
                }).start();
            }
        });
    }
    private Drawable loadImage(String path){
        Drawable drawable = null;
        try{
            drawable = Drawable.createFromStream(new URL(path).openStream(),"image.jpg");
        }catch (IOException e){
            e.printStackTrace();
        }
        return  drawable;
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值