为什么要有一个WebView
众所周知,我们可以把图片上传到Drawable或者Bipmap,但是我们不能总是在本地上传,不仅是占用大小。所以可以在后台来根据url来显示图片只要有网就能显示(之后可以做一个本地的如果没没网显示的图片)
Step1:创建头文件
在values文件夹创建一个xml文件:attr.xml内容如下
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="WebView">
<attr name="url" format="string" />
</declare-styleable>
</resources>
Step2:创建java自定义View
废话不多说直接上代码
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebView extends AppCompatImageView {
private String url;
public WebView(Context context) {
super(context);
}
public WebView(Context context, AttributeSet attrs) {
super(context, attrs);
// 获取自定义属性的值
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.WebView);
url = typedArray.getString(R.styleable.WebView_url);
typedArray.recycle();
loadUrlImage();
}
public void setUrl(String url) {
this.url = url;
loadUrlImage();
}
private void loadUrlImage() {
// 在后台线程中加载图片
new Thread(new Runnable() {
@Override
public void run() {
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream inputStream = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
// 在主线程中更新UI
post(new Runnable() {
@Override
public void run() {
setImageBitmap(bitmap);
setScaleType(ScaleType.FIT_XY);
}
});
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Step3:在xml文件中使用
例如下面的代码
<com.app.webview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:url="你的图片URL"
/>
这个com.app.webview就是存放java类的包名,这时运行发现不是闪退,就是无法显示
其实不是代码的问题,而是权限不够
在Manisft.xml中添加
<uses-permission android:name="android.permission.INTERNET" />
之后运行就ok了