Android:EditText插入图片实现图文混排

2016年03月17日 Android 16条评论 阅读13791次


Android:多行EditText打造图文混排富文本编辑器


对于插入到富文本编辑框多行EditText的图片而言,什么样的尺寸都有可能出现,或者尺寸很大,或尺寸很小。对于这种情况,出于下面两点考虑,要做相应的优化。

  • 根据用户体验至上的原则,尽量不出现水平方向的滚动条,上下方向滚动条是可以接受的
  • Android设备中很大的图片会出现OOM的异常

所以我们的优化方案就出来了:

  • 如果插入图片的宽度大于EditText控件的宽度,按照EditText控件宽度的80%作为目标宽度,对原图进行压缩
  • 如果插入图片的宽度不大于EditText控件的宽度,则直接插入原图(不进行压缩)

Activity显示时,先获得插入图片的宽度,这里用EditText控件宽度的80%(考虑到两边留一些空白更更好看一些)作为插入图片的目标宽度

点击插入图片按钮时的响应时间

public void add_img(View v) {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_PIC);
} 

从图库选择一张图之后的处理逻辑

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == PICK_PIC) {
            if (data == null) {
                Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
            } else {
                Uri uri = data.getData();
                Bitmap bitmap = getOriginalBitmap(uri);
                SpannableString ss = getBitmapMime(bitmap, uri);
                insertIntoEditText(ss);
            }
        }
    }
} 

其他关联代码

/**
 * EditText中可以接收的图片(要转化为SpannableString)
 * 
 * @param pic
 * @param uri
 * @return SpannableString
 */
private SpannableString getBitmapMime(Bitmap pic, Uri uri) {
    int imgWidth = pic.getWidth();
    int imgHeight = pic.getHeight();
    // 只对大尺寸图片进行下面的压缩,小尺寸图片使用原图
    if (imgWidth >= mInsertedImgWidth) {
        float scale = (float) mInsertedImgWidth / imgWidth;
        Matrix mx = new Matrix();
        mx.setScale(scale, scale);
        pic = Bitmap.createBitmap(pic, 0, 0, imgWidth, imgHeight, mx, true);
    }
    String smile = uri.getPath();
    SpannableString ss = new SpannableString(smile);
    ImageSpan span = new ImageSpan(this, pic);
    ss.setSpan(span, 0, smile.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;
}
private void insertIntoEditText(SpannableString ss) {
    // 先获取Edittext中原有的内容
    Editable et = et_addimage.getText();
    int start = et_addimage.getSelectionStart();
    // 设置ss要添加的位置
    et.insert(start, ss);
    // 把et添加到Edittext中
    et_addimage.setText(et);
    // 设置Edittext光标在最后显示
    et_addimage.setSelection(start + ss.length());
}
private Bitmap getOriginalBitmap(Uri photoUri) {
    if (photoUri == null) {
        return null;
    }
    Bitmap bitmap = null;
    try {
        ContentResolver conReslv = getContentResolver();
        // 得到选择图片的Bitmap对象
        bitmap = MediaStore.Images.Media.getBitmap(conReslv, photoUri);
    } catch (Exception e) {
        Log.e(TAG, "Media.getBitmap failed", e);
    }
    return bitmap;
} 

遇到的一些小问题

得到布局中EditText控件的宽度,使用ViewTreeObserver

ViewTreeObserver vto = et_addimage.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        et_addimage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        mImgViewWidth = et_addimage.getWidth();
        mInsertedImgWidth = mImgViewWidth * 0.8f;
    }
}); 

多行EditText的默认初始光标不在左上角

因为EditText默认的android:gravity属性值为center,在布局文件中把它改为top就可以了。

android:gravity="top" 

EditText,SpannableString insert-image-to-edittext

分享本文至:

WRITTEN BY

avatar
本文标签:EditText图文混排
看了本文是不是觉得很赞,那就赶紧点击下面按钮分享给身边的朋友吧!

16 条评论

  1. <a href="http://www.firestonelive.com/parajumpers-vest-men-and-women-parajumpersa">parajumpers vest men and women</a> <a href="http://www.joyhaughton.com/moncler-vest-mens-khakis-on-sale-monclera">moncler vest mens khakis on sale</a> <a href="http://www.witorodriguez.com/kvinders-asics-gel-noosa-tri-7-r%C3%B8d-guld-chaussuresb">kvinders asics gel noosa tri 7 r酶d guld</a> <a href="http://www.nantotel.com/adidas-protator-absolion-david-beckham-zapatosj">adidas protator absolion david beckham</a> <a href="http://www.insideoutelle.com/yeezy-350-boost-v2-sort-guy-obuvf">yeezy 350 boost v2 sort guy</a> <a href="http://www.montyclarkpi.com/pandora-bracelet-and-charms-deal-quiz-pandoraj">pandora bracelet and charms deal quiz</a>
    uofwrestling http://www.uofwrestling.com/

  2. <a href="http://www.sunchaseapts.com/free-run-2015-skos">free run 2015</a> <a href="http://www.financewarm.com/nike-sb-stefan-janoski-max-nero-marrone-kurpese">nike sb stefan janoski max nero marrone</a> <a href="http://www.baktindo.com/elite-nike-black-mens-ben-roethlisberger-home-jersey-nfl-7-pittsburgh-steelers-drift-fashion-nflt">elite nike black mens ben roethlisberger home jersey nfl 7 pittsburgh steelers drift fashion</a> <a href="http://www.iranqnap.com/hermes-h-belt-sizes-hermesr">hermes h belt sizes</a> <a href="http://www.classiccarslb.com/air-jordan-1-retro-infrarojo-zephyr-chaussuresd">air jordan 1 retro infrarojo zephyr</a> <a href="http://www.dkslawn.com/bon-march%C3%A9-nike-free-tr2-hommes-argent-sportsd">bon march茅 nike free tr2 hommes argent</a>
    vbchopshop http://www.vbchopshop.com/

  3. <a href="http://www.factorxf.com/nike-flyknit-trainer-blanc-noir-for-vente-australia-butye">nike flyknit trainer blanc noir for vente australia</a> <a href="http://www.meinscreen.com/nike-air-huarache-gr%C3%B8nn-lantern-obuvd">nike air huarache gr酶nn lantern</a> <a href="http://www.melbabishop.com/nike-flynit-air-max-lilla-brun-obuve">nike flynit air max lilla brun</a> <a href="http://www.prototipes.com/ralph-lauren-polo-green-label-version-polob">ralph lauren polo green label version</a> <a href="http://www.coberturatic.com/coach-purses-and-matching-wallets-coachr">coach purses and matching wallets</a> <a href="http://www.falsterboyoga.com/nobis-coats-sale-2017-nobisb">nobis coats sale 2017</a>
    polyphonyma http://www.polyphonyma.com/

  4. <a href="http://www.mundidopets.com/nike-mens-adoree-jackson-game-light-blue-home-jersey-tennessee-titans-nfl-25-nflt">nike mens adoree jackson game light blue home jersey tennessee titans nfl 25</a> <a href="http://www.talkofig.com/hermes-kelly-shoulder-handbag-clemence-leather-lagoon-green-silver-32cm-hermesa">hermes kelly shoulder handbag clemence leather lagoon green silver 32cm</a> <a href="http://www.avonew.com/family-forever-pandora-safety-chain-pandorar">family forever pandora safety chain</a> <a href="http://www.bandqlocal.com/nike-air-zoom-vomero-9-gr%C3%A5-obuve">nike air zoom vomero 9 gr氓</a> <a href="http://www.dolcemialuxe.com/parajumpers-coat-drawing-front-and-back-parajumpersb">parajumpers coat drawing front and back</a> <a href="http://www.genevacollins.com/air-max-essential-90-green-sneakerc">air max essential 90 green</a>
    metinmilli http://www.metinmilli.com/

  5. <a href="http://www.buysfohomes.com/mujeres-salomon-speed-cross-3-negro-rojo-scarpeb">mujeres salomon speed cross 3 negro rojo</a> <a href="http://www.namboathood.com/ogc-nice-25-cypricn-home-soccer-club-jersey-nfls">ogc nice 25 cypricn home soccer club jersey</a> <a href="http://www.pennphone.com/adidas-damian-lillard-3-grau-gelb-scarpeg">adidas damian lillard 3 grau gelb</a> <a href="http://www.proyectosuraj.com/air-jordan-12-wolf-grau-low-obuvc">air jordan 12 wolf grau low</a> <a href="http://www.sitesforu.com/air-jordan-3.5-rosa-svart-scarpea">air jordan 3.5 rosa svart</a> <a href="http://www.vloansltd.com/dam%C3%A4nner-nike-free-6.0-gr%C3%BCn-rot-schuheb">dam盲nner nike free 6.0 gr眉n rot</a>
    prorilasia http://www.prorilasia.com/

  6. avatar lorenaflowers

    <a href="http://www.sinfoniamktg.com/nike-kobe-7-bleu-jaune-lab-trainersd">nike kobe 7 bleu jaune lab</a> <a href="http://www.mrshoover.com/nike-kobe-8-sort-and-guld-guide-chaussuresm">nike kobe 8 sort and guld guide</a> <a href="http://www.valomak.com/blanc-polo-shirt-with-bleu-collar-poloa">blanc polo shirt with bleu collar</a> <a href="http://www.inklinktatoo.com/air-jordan-1-pinnacle-hvit-queen-scarpek">air jordan 1 pinnacle hvit queen</a> <a href="http://www.adracingworld.com/blumen-kleid-f%C3%BCr-m%C3%A4dchen-dresse">blumen kleid f眉r m盲dchen</a> <a href="http://www.tentoledo.com/air-jordan-15-retro-2017-release-footi">air jordan 15 retro 2017 release</a>
    lorenaflowers http://www.lorenaflowers.com/

  7. avatar chiveshow

    <a href="http://www.goeaglepointe.com/nike-air-force-1-mid-bianca-marrone-gum-schuheg">nike air force 1 mid bianca marrone gum</a> <a href="http://www.purofairtrade.com/wei%C3%9F-ralph-lauren-swim-shorts-poloz">wei脽 ralph lauren swim shorts</a> <a href="http://www.thedamnsels.com/nike-dunk-hi-tout-star-2015-chaussuresa">nike dunk hi tout star 2015</a> <a href="http://www.toockbespoke.com/air-max-90-hyperfuse-noir-rose-schuhed">air max 90 hyperfuse noir rose</a> <a href="http://www.emenucards.com/air-jordan-11-ovo-negro-ice-scarpea">air jordan 11 ovo negro ice</a> <a href="http://www.midihair.com/nike-mercurial-vapor-dark-gr%C3%B8n-knight-kurpesf">nike mercurial vapor dark gr酶n knight</a>
    chiveshow http://www.chiveshow.com/

  8. avatar eyesocal

    <a href="http://www.chenmingusa.net/nike-air-max-zero-p%C3%BArpura-items-chaussuresb">nike air max zero p煤rpura items</a> <a href="http://www.chestnuthillnursery.net/nike-air-max-tailwind-8-gris-oro-butya">nike air max tailwind 8 gris oro</a> <a href="http://www.chromacell.net/adidas-springblade-drive-2-sort-l%C3%B8b-sko-online-schuhed">adidas springblade drive 2 sort l酶b sko online</a> <a href="http://www.citipark.net/jordan-5-hvid-bl%C3%A5-guld-chaussurese">jordan 5 hvid bl氓 guld</a> <a href="http://www.clickexplosions.net/nike-zoom-structure-19-orange-gr%C3%B8n-obuvf">nike zoom structure 19 orange gr酶n</a> <a href="http://www.cluebdistribuzione.net/nike-air-max-97-sort-camo-kurpese">nike air max 97 sort camo</a>
    eyesocal http://www.eyesocal.net/

  9. avatar hkyahao

    <a href="http://www.sohbetikiz.com/nike-free-3.0-focfly-so-barato-years-runninga">nike free 3.0 focfly so barato years</a> <a href="http://www.akkordiki.com/air-jordan-retro-12-cioccolato-scarpee">air jordan retro 12 cioccolato</a> <a href="http://www.torrentslot.com/nike-air-max-90-hyperfuse-oransje-lilla-runningg">nike air max 90 hyperfuse oransje lilla</a> <a href="http://www.familycarepc.com/nike-air-max-tailwind-8-dam%C3%A4nner-schwarz-schuhei">nike air max tailwind 8 dam盲nner schwarz</a> <a href="http://www.alizatrade.com/volcom-outdoors-snapback-cap-hath">volcom outdoors snapback cap</a> <a href="http://www.auroragenri.com/p%C3%BArpura-nike-huarache-basebtodas-cleats-trainersce">p煤rpura nike huarache basebtodas cleats</a>
    hkyahao http://www.hkyahao.com/

  10. avatar pragaoviedo

    <a href="http://www.teddevans.com/nike-dunk-high-hellboy-rot-schuhej">nike dunk high hellboy rot</a> <a href="http://www.cateycontrols.com/nike-sb-stefan-janoski-max-trainers-in-grau-schuhei">nike sb stefan janoski max trainers in grau</a> <a href="http://www.prodomfactory.com/air-jordan-cp3-svart-r%C3%B8d-obuvj">air jordan cp3 svart r酶d</a> <a href="http://www.tonyaespinoza.com/nike-flyknit-air-vapormax-2018-viola-bianca-scarpel">nike flyknit air vapormax 2018 viola bianca</a> <a href="http://www.nemagrp.com/femmes-marine-bleu-converse-chaussures-chaussuresh">femmes marine bleu converse chaussures</a> <a href="http://www.viajesclic.com/tutti-bianca-pelle-nike-shox-scarpeh">tutti bianca pelle nike shox</a>
    pragaoviedo http://www.pragaoviedo.com/

  11. avatar merleflugge

    <a href="http://www.bowtieorg.com/nike-air-max-lebron-8-all-black-shoesl">nike air max lebron 8 all black</a> <a href="http://www.shaneboothmx.com/ralph-lauren-equestrian-handbag-poloh">ralph lauren equestrian handbag</a> <a href="http://www.basarancarpet.com/nike-elastico-superfly-ic-gul-gr%C3%B8n-sort-skok">nike elastico superfly ic gul gr酶n sort</a> <a href="http://www.freedhamaal.com/nike-air-max-90-hyperfuse-herren-rot-schuheh">nike air max 90 hyperfuse herren rot</a> <a href="http://www.borbonecoffe.com/men-nike-air-max-tailwind-7-black-blue-white-shoesk">men nike air max tailwind 7 black blue white</a> <a href="http://www.cammaara.com/alle-hvid-nike-shox-herre-skol">alle hvid nike shox herre</a>
    merleflugge http://www.merleflugge.com/

  12. avatar converse salg rosa

    <a href="http://www.ankaraoyunevi.com/jordan-v5-grown-canvas-low-svart-obuvi">jordan v5 grown canvas low svart</a> <a href="http://www.iotlsebring.com/nike-huarache-r%C3%B8d-gr%C3%A5-svart-obuvk">nike huarache r酶d gr氓 svart</a> <a href="http://www.joshsingleton.com/nike-tiempo-legend-v-r%C3%B8d-hvit-obuvi">nike tiempo legend v r酶d hvit</a> <a href="http://www.amesecolombia.com/hombres-nike-air-huarache-negro-2-zapatosl">hombres nike air huarache negro 2</a> <a href="http://www.flatshotgame.com/nike-tiempo-legend-arancia-and-bianca-scarpeh">nike tiempo legend arancia and bianca</a> <a href="http://www.myrumpun.com/nike-cortez-nylon-men-camo-red-shoesk">nike cortez nylon men camo red</a>
    converse salg rosa http://www.actuelvet.com/converse-salg-rosa-obuvi

  13. avatar nchfnj

    <a href="http://www.magnindesign.com/stephen-curry-one-sko-for-salg-runningd">stephen curry one sko for salg</a> <a href="http://www.spinecareuk.com/rob-gronkowski-arizona-jersey-nflh">rob gronkowski arizona jersey</a> <a href="http://www.danteb.com/nike-air-max-2014-azul-zapatosh">nike air max 2014 azul</a> <a href="http://www.karlisteffy.com/nike-air-max-tailwind-5-oransje-lilla-scarpea">nike air max tailwind 5 oransje lilla</a> <a href="http://www.festadoano.com/golden-state-warriors-new-era-nba-retro-word-9fifty-snapback-cap-hati">golden state warriors new era nba retro word 9fifty snapback cap</a> <a href="http://www.bursagti.com/nike-air-max-chase-l%C3%A6der-trainersb">nike air max chase l忙der</a>
    nchfnj http://www.nchfnj.com/

  14. avatar lintvan

    <a href="http://www.rcrocs.com/ray-ban-classic-wayfarer-xl-sunglassesh">ray ban classic wayfarer xl</a> <a href="http://www.moreheaddotts.com/nike-air-huarache-noir-blanc-noir-chaussuresl">nike air huarache noir blanc noir</a> <a href="http://www.qgchsmrt.com/adidas-neo-blanc-philippines-chaussuresl">adidas neo blanc philippines</a> <a href="http://www.firagandia.com/dam%C3%A4nner-air-jordan-retro-13-wei%C3%9F-rosa-schuhej">dam盲nner air jordan retro 13 wei脽 rosa</a> <a href="http://www.lmladeco.com/dam%C3%A4nner-nike-air-max-90-wei%C3%9F-schuhei">dam盲nner nike air max 90 wei脽</a> <a href="http://www.brinkmanmdc.com/air-max-nike-sko-svart-obuvj">air max nike sko svart</a>
    [url=http://www.lintvan.com/]lintvan[/url]

  15. avatar eisenhards

    <a href="http://www.avantajreyonu.com/nike-tiempo-legend-v-grey-shoesk">nike tiempo legend v grey</a> <a href="http://www.oranjeskishop.com/ray-ban-justin-rubber-havana-sunglassesh">ray ban justin rubber havana</a> <a href="http://www.johannafrost.com/nike-sock-dart-sp-hommes-rose-chaussuresl">nike sock dart sp hommes rose</a> <a href="http://www.rolandviet.com/nike-kyrie-4-femmes-year-of-the-monkey-chaussuresl">nike kyrie 4 femmes year of the monkey</a> <a href="http://www.classmedya.com/frau-nike-kyrie-3-schwarz-wei%C3%9F-schuhej">frau nike kyrie 3 schwarz wei脽</a> <a href="http://www.anteageserums.com/supreme-x-nike-blazer-low-rosa-schuhei">supreme x nike blazer low rosa</a>
    eisenhards http://www.eisenhards.com/

  16. avatar 乐悠游

    有兴趣玩玩,收下这个,谢谢

欢迎留言




用户登录

sitemap