Custom image/Text hybrid Layout View myimagetextview

Source: Internet
Author: User

Textview itself supports text-to-text mixing. on a mobile phone, text-to-text mixing through textview may be difficult to achieve the effect of browsers on PCs, especially for publishing systems that support multiple tags.


1. Examples of how to use textview to achieve text-and-text mixing are easily found on the Internet, mostly in the following format:

Textview TV _content;

TV _content.settext (html. fromhtml (item. getcontent (), getimagegetter (), null ));


Private imagegetter = NULL; private Map <string, urldrawable> imagehashmap = NULL; private imagegetter getimagegetter () {If (imagehashmap = NULL) {imagehashmap = new hashmap <string, urldrawable> (2);} If (imagegetter = NULL) {imagegetter = new imagegetter () {// It is a time-consuming operation to obtain images through the network. It is best not to place the images in the main thread, otherwise, blocking may occur. @ Overridepublic drawable getdrawable (string source) {string key = md5.encoderbymd5 (source); urldrawable = imagehashmap. get (key); If (urldrawable = NULL) {urldrawable = new urldrawable (); imagehashmap. put (Key, urldrawable); // get the actual sourceimagegetterasynctask. start (mcontext, urldrawable, source, Handler) ;}return urldrawable ;};}return imagegetter ;}private handler = new handler () {@ overridepublic void handlemessage (Android. OS. message MSG) {If (MSG. what = imagegetterasynctask. ondrawableprepared) {refreshnewsimage (MSG) ;}}; private void refreshnewsimage (Android. OS. message MSG) {notifydatasetchanged ();}

You need to set the size of the image to be displayed:

Drawable. setbounds (0, 0, bitmap. getwidth (), bitmap. getheight ());


2. It is normal to use listviewitem in general, but if it is a subview of scrollview, an exception will be thrown when there is an image (this is the case on the company testing machine, other environments are not verified ). We recommend that you use a custom view. The basic idea is to use spannablestringbuilder to split images and non-image content, and then create images and non-image views one by one. This method is applicable to similar News presentations that require highly customized UI.


2.1 content_textview.xml: used to display content other than the image

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    style="@style/Style_NewsText_Content"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:paddingLeft="10dp"    android:paddingRight="10dp"    android:typeface="normal" ></TextView>


2.2 content_imageview.xml: used to display images and image descriptions, for example, "[Figure 1]"
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:layout_gravity="center_horizontal"    android:orientation="vertical"     android:paddingTop="5dp">    <ImageView        android:id="@+id/content_imageview_image"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:adjustViewBounds="true"        android:baselineAlignBottom="true"        android:contentDescription="@string/xxx"        android:minHeight="30dp"        android:minWidth="30dp"        android:paddingBottom="5dp"        android:scaleType="centerInside" >    </ImageView>    <TextView        android:id="@+id/content_imageview_title"        style="@style/Style_NewsText_Content"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:paddingBottom="5dp"        android:singleLine="false"        android:textColor="@color/text_b0b0b0"        android:textSize="@dimen/font_small" >    </TextView></LinearLayout>


2.3 vertical_linearlayout.xml: Root View, used to insert content to be displayed

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="vertical" >    </LinearLayout>


2.4 myimagetextview. JVA: class for implementing text/Text Mixing
Public class myimagetextview extends framelayout {// corresponding viewprivate linearlayout mcontentview = NULL; // corresponding data private charsequence mdata = NULL; private string [] mimageurl = NULL; private imageview [] mimage = NULL; private int mimagebaseindex = 1; // starting from [Figure 1] // whether hyperlink is supported click private Boolean suppmovmovementmethod = false; // whether to display the graph index private Boolean showimageindex = false; Public myimagetextview (context) {thi S (context, null);} public myimagetextview (context, attributeset attrs) {This (context, attrs, 0);} public myimagetextview (context, attributeset attrs, int defstyle) {super (context, attrs, defstyle); Init () ;}private void Init () {setdrawingcacheenabled (false); setclipchildren (false); mcontentview = (linearlayout) layoutinflater. from (getcontext ()). inflate (R. layout. vertical_linearlayout, NUL L); addview (mcontentview);}/*** set the content to be displayed * @ Param content */Public void settext (charsequence content) {try {If (textutils. isempty (content) {return;} If (content. equals (mdata) {return;} mdata = content; mcontentview. removeallviews (); // first clear the previously added sub-view int viewindex = 0; int Len = content. length (); spannablestringbuilder style = new spannablestringbuilder (content); imagespan [] imgary = style. getspans (0, l En, imagespan. class); If (imgary = NULL | imgary. length <= 0) {addtextview (content, viewindex); return;} int Pos = 0; int start = 0; int end = 0; imagespan IMG = NULL; mimageurl = new string [imgary. length]; mimage = new imageview [imgary. length]; for (INT I = 0; I  0 & Pos <Len) {addtextview (style. subsequence (Pos, Len), viewindex);} requestlayout (); invalidate (); // on a UI thread} catch (exception ex) {}} private void addtextview (charsequence text, int viewindex) {textview TV = (textview) layoutinflater. from (getcontext ()). inflate (R. layout. content_textview, null); mcontentview. addview (TV, viewindex); TV. settext (text); If (supportmovementmethod) {changelink (TV) ;}} private void addimageview (INT index, int viewindex) {view parent = layoutinflater. from (getcontext ()). inflate (R. layout. content_imageview, null); mimage [Index] = (imageview) parent. findviewbyid (R. id. content_imageview_image); textview tvtitle = (textview) parent. findviewbyid (R. id. content_imageview_title); If (showimageindex) {// The image title here, you can also analyze the tvtitle by using attributes such as the title/ALT of the  label. settext ("[figure" + integer. tostring (mimagebaseindex + index) + "]"); tvtitle. setvisibility (view. visible);} else {tvtitle. setvisibility (view. gone);} mcontentview. addview (parent, viewindex); setimage (parent, mimage [Index], mimageurl [Index]);} private void setimage (view parent, imageview IV, string picurl) {If (P Icurl! = NULL & picurl. trim (). length ()> 0) {parent. setvisibility (view. visible); IV. setimageresource (R. drawable. weibo_pic_loading); size = setpic (IV, picurl); If (size. getheight ()> 0 & size. getwidth ()> 0) {parent. requestlayout () ;}} else {parent. setvisibility (view. gone) ;}} private size setpic (imageview logoview, string logourl) {// asynchronously load Image Code slightly return xxxfilemanager. getinstance (). setimagebitmapwithmemorycac He (getcontext (), logoview, logourl, xxxfilemanager. getimagetlrucache (), getcontext (). getclass (). getname (), false);}/*** call * @ Param fileurl */Public void setpic (string fileurl) {If (mimage! = NULL & mimageurl! = NULL &&! Textutils. isempty (fileurl) {string source = NULL; For (INT I = 0; I <mimageurl. length & I <mimage. length; I ++) {source = mimageurl [I]; If (! Textutils. isempty (source) {If (fileurl. equals (source) {setpic (mimage [I], source); mimage [I]. getparent (). requestlayout (); break ;}}}/ *** sets whether a hyperlink is supported. Click */Public void setsuppmovmovementmethod (Boolean suppmovmovementmethod) {This. supportmovementmethod = supportmovementmethod;}/*** sets whether to display the graph Index * @ Param showimageindex */Public void setshowimageindex (Boolean showimageindex) {This. showimageindex = showimagei Ndex;}/*** sets the textview hyperlink to jump to * @ Param TV */private void changelink (textview TV) {TV. setmovementmethod (linkmovementmethod. getinstance (); charsequence text = TV. gettext (); If (Text instanceof spannable) {int end = text. length (); spannable sp = (spannable) TV. gettext (); urlspan [] URLs = sp. getspans (0, end, urlspan. class); If (URLs = NULL | URLs. length <= 0) {return;} spannablestringbuilder style = New spannablestringbuilder (text); urlspan [] urlsn = style. getspans (0, end, urlspan. Class); If (urlsn = NULL | URLs. length! = Urlsn. length) {return;} // cyclically sends the link to urlspan url = NULL; For (INT I = 0; I <URLs. length & I <urlsn. length; I ++) {url = URLs [I]; myurlspan = new myurlspan (getcontext (), URL. geturl (); style. removespan (urlsn [I]); style. setspan (myurlspan, SP. getspanstart (URL), SP. getspanend (URL), spannable. span_exclusive_inclusive);} TV. settext (style) ;}} public int getimagecount () {int CNT = mimagebase Index; If (mimage! = NULL & mimageurl! = NULL) {CNT + = mimage. length;} return CNT;} public void setmimagebaseindex (INT baseindex) {This. mimagebaseindex = baseindex;} public charsequence getmdata () {return mdata ;}}


2.5 myurlspan. Java: defines a clickable span. Click the hyperlink to open or modify a webpage/file in the browser.
public class MyURLSpan extends ClickableSpan {private Context context = null;private String mUrl     = null;;public MyURLSpan(Context context,String url) {this.context = context;this.mUrl = url;}@Overridepublic void onClick(View widget) {if (URLUtil.isNetworkUrl(mUrl)) {XXXUtils.openMyWebBrowser(this.context,this.context.getResources().getString(R.string.newstext_hyperlink),this.mUrl);}}}


3. Easy to use. You can reference it in an XML file or create a view dynamically.

3.1 reference in XML

        <ScrollView            android:id="@+id/XXX_ScrollView"            android:layout_width="fill_parent"            android:layout_height="fill_parent" >            <LinearLayout                android:id="@+id/XXX_Parent"                android:layout_width="fill_parent"                android:layout_height="wrap_content"                android:orientation="vertical"                android:visibility="gone" >                ……                <LinearLayout                    android:layout_width="fill_parent"                    android:layout_height="wrap_content"                    android:orientation="vertical"                    android:paddingBottom="5dp"                    android:paddingTop="10dp" >                    <XXX.textview.MyImageTextView                        android:id="@+id/XXX_Content"                        android:layout_width="fill_parent"                        android:layout_height="wrap_content"                        android:paddingLeft="10dp"                        android:paddingRight="10dp" >                    </XXX.textview.MyImageTextView>                    <RelativeLayout                        android:id="@+id/XXX_PayViewParent"                        android:layout_width="fill_parent"                        android:layout_height="wrap_content"                        android:paddingBottom="10dp"                        android:paddingTop="5dp"                        android:visibility="gone" >                        <XXX.textview.MyImageTextView                            android:id="@+id/XXX_PayContent"                            android:layout_width="fill_parent"                            android:layout_height="wrap_content"                            android:paddingLeft="10dp"                            android:paddingRight="10dp"                            android:visibility="gone" >                        </XXX.textview.MyImageTextView>                        <RelativeLayout                            android:id="@+id/XXX_PayLock"                            android:layout_width="fill_parent"                            android:layout_height="wrap_content"                            android:background="@drawable/xxx_paylock_bg"                            android:gravity="center_horizontal" >                            <ImageView                                android:id="@+id/xxx_Lock"                                android:layout_width="wrap_content"                                android:layout_height="wrap_content"                                android:layout_centerVertical="true"                                android:layout_marginRight="5dp"                                android:contentDescription="@string/xxx"                                android:padding="5dp"                                android:src="@drawable/xxx_paylock_icon" >                            </ImageView>                            ……                        </RelativeLayout>                    </RelativeLayout>                </LinearLayout>            </LinearLayout>        </ScrollView>


3.2 Java code, set the display content

itvFreeContent = (MyImageTextView) this.findViewById(R.id.XXX_Content);<span style="white-space:pre"></span>itvFreeContent.setSupportMovementMethod(true);<span style="white-space:pre"></span>//itvFreeContent.setShowImageIndex(true);<span style="white-space:pre"></span>itvFreeContent.setText(Html.fromHtml(formatContent(content)));

Of course, you also need to add the code after the asynchronous download of the image, such:

private void initHandler() {this.mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case KLoadImageOver:itvFreeContent.setPic(msg.getData().getString("fileURL"));break;default:break;}}};}

Actual (Part intercepted ):



4. The second method needs to be extended. If the displayed content has a hyperlink and the displayed object in the hyperlink is an image, you need to add a click event to the image. For the click jump, see myurlspan. onclick.

For image download, we recommend a third-party library Android-universal-image-loader.


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.