Android Graphics Mixed (one)-achieve edittext graphics mixed insert Upload

Source: Internet
Author: User

Some time ago to do an Android Conference management system, project requirements related to the edittext of the picture and text mixed,

In the meeting details, you need to support mixed insertion of text and pictures, demonstrating examples of input:
When the meeting is created, save the data to the server, and then view the meeting that you just created.

I. Clear Needs
First, click on the "Meeting details" text box, the normal input text, and then click the picture icon in the lower left corner, enter the system of the album used to select a picture and insert into the text box, you can also rest the cursor in the middle of any text, complete the insertion of the picture, back to the building can delete the text, you can delete the

Second, the realization of ideas

如果要在一个EditText中显示图片,首先得简单了解一下SpannableString和ImageSpan的使用。在上面的图文混排的EditText中,虽然看到了生动的图文效果,但是实际上输出EditText的get Text().toString(),其实是:"插入一张图片<img src=\"" + url1+ "\" />。再插入一张图片<img src=\"" + url2+ "\" />。"。也就是说,当我选择图片插入到EditText中时,虽然显示了该图片,但是插入进去的其实是这个图片的url。当我保存这条记录时,传给服务器的值就是:"插入一张图片<img src=\"" + url1+ "\" />。再插入一张图片<img src=\"""\" />。"这部分代码如下:

1. Click the image button to enter the system album

    /**     * 图文详情页面选择图片     */    publicvoidgetImage() {        new Intent(Intent.ACTION_GET_CONTENT);        intent.addCategory(Intent.CATEGORY_OPENABLE);        intent.setType("image/*");        0);    }

2. Get to the picture and call the interface to upload the picture to the server, upload the URL of the picture that was returned to the server after the success

    @Override    protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {if(ResultCode = = Result_ok && Requestcode = =0) {Contentresolver resolver = Getcontentresolver ();//Get the URI of the pictureUri Originaluri = Data.getdata (); Bitmap =NULL;Try{Bitmap Originalbitmap = Bitmapfactory.decodestream (Resolver.openinputstream (Originaluri)); Bitmap = Imageutils.resizeimage (Originalbitmap, -);//Convert the bitmap of the original image to a file                //Upload the file and get the URL                NewThread (NewRunnable () {@Override                     Public void Run() {Insertpic (bitmap,0);            }}). Start (); }Catch(FileNotFoundException e)            {E.printstacktrace (); } }}

3. By executing the Insertpic () method, get to the URL and do some processing so that it appears in the EditText

    /** * Insert Picture * /    Private void Insertpic(Bitmap BM,Final intIndex) {Ajaxparams params =NewAjaxparams ();Try{Params.put ("Image", Leoutils.savebitmap (BM)); }Catch(FileNotFoundException e)        {E.printstacktrace (); } finalhttp fh =NewFinalhttp (); System.out.println ("params="+ params.tostring ()); Fh.post (Httpurlconstant.upload_pic, params,NewAjaxcallback<object> () {@Override             Public void onfailure(Throwable T,intErrorno, String strMsg) {Super. OnFailure (t, Errorno, STRMSG); Toastutil.show (Getapplicationcontext (),"Picture upload failed, please check the network"); }@Override             Public void onsuccess(Object t) {Super. onsuccess (t); System.out.println (T.tostring ());Try{Jsonobject Jsonobject =NewJsonobject (T.tostring ()); String URL = jsonobject.getstring ("Recordname");Switch(index) { Case 0://Create Imagespan object based on bitmap objectImagespan Imagespan =NewImagespan (createmeetingactivity. This, bitmap);//Create a Spannablestring object to insert an image encapsulated with a Imagespan objectString Tempurl ="  " "+ URL +"\"/> "; Spannablestring spannablestring =NewSpannablestring (Tempurl);//Replace the string you specified with the Imagespan objectSpannablestring.setspan (Imagespan,0, Tempurl.length (), spannable.span_exclusive_exclusive);//Append the selected picture to the cursor position in the EditText                        intindex = Et_detail.getselectionstart ();//Get cursor locationEditable Edit_text = Et_detail.geteditabletext ();if(Index <0||                        Index >= edit_text.length ()) {edit_text.append (spannablestring); }Else{Edit_text.insert (index, spannablestring); } System.out.println ("inserted Picture:"+ spannablestring.tostring ()); Break; Case 1://code unrelated to this case                         Break; }                }Catch(Jsonexception e)                {E.printstacktrace ();    }            }        }); }

The above comments are written in detail, even if you do not know spannerstring and Imagespan before, I believe you can appreciate their usage. At this point, the Android EditText graphics mixed insertion requirements have been completed.

Iii. Additional Information
Q1: Why upload the image to the server to get the URL?
A1:PM requires each insertion of a picture to the interface to upload the image to the server, the interface will return the image URL, although this is not a good solution. If you do not need to save the text mixed insert content, then you do not have to do this step, in Imagespan replacement, you can use any character substitution, because for spanneblestring, the inserted picture is actually some characters, This can be verified by outputting edittext.gettext (). ToString ().

// 用ImageSpan对象替换spannableString.setSpan0"图片1", Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Q2: Why do you want to wrap the URL of the image again into a string with an IMG tag?

A2: 因为项目的另外一个需求是编辑会议,也就是图文混合插入的内容支持以后的再次编辑。当调用会议编辑接口时,会返回会议详情的数据,这些数据就是:"插入一张图片<img src=\"" + url1+ "\" />。再插入一张图片<img src=\"" + url2+ "\" />。"为了让会议详情页面的图文回显到EditText中,我会对这些字符串通过正则匹配"\">,如果匹配到这种格式,就代表它是一个图片,然后通过一些处理将图片回显出来。

Android Text Mix (one)-achieve edittext graphics and text mixed insert upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.