我正在开发 < 新闻应用程序,我需要在 Textview 中一致地显示图像和文本。 这是我想在应用程序中显示的确切消息。
所以我写了以下代码:
public class NewsActivity extends AppCompatActivity implements FeedAdapter.OnItemClickListener, Html.ImageGetter
{
TextView textViewBody;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
textViewBody = findViewById(R.id.textview_newsBody);
Intent intent = getIntent();
String body = intent.getStringExtra(EXTRA_BODY);
body = body.replace("<", "<").replace(">", ">");
Spanned spanned = Html.fromHtml(body, this, null);
textViewBody.setText(spanned);
}
@Override
public Drawable getDrawable(String source)
{
LevelListDrawable drawable = new LevelListDrawable();
Drawable empty = getResources().getDrawable(R.drawable.ic_arxiv);
drawable.addLevel(0, 0, empty);
drawable.setBounds(0,0,empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
new LoadImage().execute(source, drawable);
return drawable;
}
class LoadImage extends AsyncTask<Object, Void, Bitmap>
{
private LevelListDrawable mDrawable;
@Override
protected Bitmap doInBackground(Object... params) {
String source = (String) params[0];
mDrawable = (LevelListDrawable) params[1];
Log.d(TAG, "doInBackground " + source);
try {
InputStream is = new URL(source).openStream();
return BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap)
{
Log.d(TAG, "onPostExecute drawable " + mDrawable);
Log.d(TAG, "onPostExecute bitmap " + bitmap);
if (bitmap != null) {
BitmapDrawable d = new BitmapDrawable(getApplicationContext().getResources(), bitmap);
mDrawable.addLevel(1, 1, d);
mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
mDrawable.setLevel(1);
// i don't know yet a better way to refresh TextView
// mTv.invalidate() doesn't work as expected
CharSequence t = textViewBody.getText();
textViewBody.setText(t);
textViewBody.refreshDrawableState();
}
}
}
尝试打开此新闻时,每张图片都会出现 MalformedURLException:
W/System.err: java.net.MalformedURLException: Protocol not found: "https://metbuat.az/uploads/295/7f54088035-img6105.jpg"
如果我将 URL 复制粘贴到浏览器,则可以,并且协议已经提供。
为什么我仍然收到此异常?