如何在android中使用imagegetter设置textview的宽度和高度

时间:2017-01-12 07:26:21

标签: android textview

我的应用包含textview和字符串,该字符串包含 img标记 html代码,我使用 ImageGetter 将该字符串分配给textview显示图像,图像正在应用程序中检索和显示。但该字符串还包含样式标记,其中包含高度和宽度属性,现在我需要获取这些属性值并分配给onPostExecute()中的mDrawable。

以下是我的 MainActivity

public class MainActivity extends Activity implements ImageGetter {
private final static String TAG = "MainActivity";
private TextView mTv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String imgs = "<p><img alt=\"\" src=\"https://rukminim1.flixcart.com/image/832/832/screwdriver-set/6/3/f/41pcs-aecone-original-imaedhrtthffafup.jpeg?q=70\" style=\"height:100px; width:100px\" />";
    Spanned spanned = Html.fromHtml(imgs, this, null);
    mTv = (TextView) findViewById(R.id.text);
    mTv.setText(spanned);

}
@Override
public Drawable getDrawable(String source) {
    LevelListDrawable d = new LevelListDrawable();
    Drawable empty = getResources().getDrawable(R.mipmap.ic_launcher);
    d.addLevel(0, 0, empty);
    d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());
    new LoadImage().execute(source, d);

    return d;
}

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 " + params[0]);
        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(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 = mTv.getText();
            mTv.setText(t);
        }
    }
}

}

0 个答案:

没有答案