有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在textview中用img html显示图像

我想在文本视图中显示图像。我在res/drawable/img中有一个图像。巴布亚新几内亚 这是我的代码:

String img="<img src='file:///res/drawable/img.png' />";
txt_html.append(Html.fromHtml(img)); 

但这不是工作

知道吗


共 (1) 个答案

  1. # 1 楼答案

    要从web下载图像并在textView中显示,我使用了以下方法:

    public class MainActivity extends ActionBarActivity {
    
    public String htmlContent;
    int ScreenW,ScreenH;
    Context context;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_news);
    
        this.context = getBaseContext();
    
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        float dpWidth = displayMetrics.widthPixels;
        float dpHeight = displayMetrics.heightPixels;
    
        ScreenW = (int) dpWidth;
        ScreenH = (int) dpHeight;
    
        try {
    
            ((TextView) findViewById(R.id.tv_my_content)).setText(Html.fromHtml(htmlContent, Images, null));
        }
        catch (Exception ex)
        {
            
        }
    }
    
    private Html.ImageGetter Images = new Html.ImageGetter() {
    
        public Drawable getDrawable(String source) {
            
            Drawable drawable = null;
    
            FetchImageUrl fiu = new FetchImageUrl(context,source);
            try {
                fiu.execute().get();
                drawable = fiu.GetImage();
            }
            catch (Exception e) {
                drawable = getResources().getDrawable(R.drawable.img_news);
            }
             // to display image,center of screen
            int imgH = drawable.getIntrinsicHeight();
            int imgW = drawable.getIntrinsicWidth();
            int padding =20;
            int realWidth = ScreenW-(2*padding);
            int realHeight = imgH * realWidth/imgW;
            drawable.setBounds(padding,0,realWidth ,realHeight);
            return drawable;
        }
    };
    }
    

    FetchImageUrl类是:

    public class FetchImageUrl extends AsyncTask<String, String, Boolean> {
    
    
    String imageUrl;
    Context context;
    protected Drawable image;
    
    public FetchImageUrl(Context context, String url)
    {
        this.imageUrl = url;
        image = null;
        this.context = context;
    }
    
    public Drawable GetImage()
    {
        return image;
    }
    
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    @Override
    protected Boolean doInBackground(String... args) {
        try {
            InputStream input_stream = (InputStream) new URL(imageUrl).getContent();
            image = Drawable.createFromStream(input_stream, "src name");
            return true;
    
        }
        catch (Exception e)
        {
            image = null;
        }
        return false;
    }
    
    
    @Override
    protected void onPostExecute(Boolean result) {
    
    }}