在TextView或者EditView中添加图片

因为EditView是继承TextView的所以TextView中能实现图片添加,那么EditView也能轻易的实现

private void initView() {
        editText = (EditText) findViewById(R.id.edit);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("");

        //从drawable资源中获取随机图片资源
        SpannableString ssb= RandomBitmap();
        editText.append(ssb != null ? ssb : "");
        ssb = RandomBitmap();
        textView.append(ssb != null ? ssb : "");
    }
    
    public SpannableString RandomBitmap(){
        try {

            //有12张图片
            final int randomInt = (int) (Math.random()*12);
            Field fields = R.drawable.class.getDeclaredField("autobbs_face1");
            final int resourceId = fields.getInt(null) + randomInt;
            ImageSpan imageSpan = new ImageSpan(this, 
                    resourceId != -1 ? resourceId : R.drawable.ic_launcher);
            SpannableString ssb = new SpannableString("autobbs");

            //这里的参数0 ,6指的是图片替换的字符的起始和结束位置。

            ssb.setSpan(imageSpan, 0, 6, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            return ssb;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

你可能感兴趣的:(android,textview,文本中添加图片)