Show Image in TextView

前端 未结 3 1536
花落未央
花落未央 2021-02-09 20:14

I wish to show Images in TextView. My Images are saved in res/raw directory. I tried using HTML.ImageGetter but could not find a complete reference for same.

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-09 20:30

    Give this a try so you don't have to hack your use of TextView. This will allow you to account for an arbitrary number of images tagged in the source string. it will also allow for adjacent images, and allow for empty leading or trailing text strings.

    LinearLayout parent = //get parent layout
    String input = //get input
    LayoutInflater inflater = this.getLayoutInflater();
    int imageIndex = input.indexOf(" -1){
        TextView tv = inflater.inflate(R.layout.my_textview, null);
        tv.setText(input.substring(0, imageIndex));
    
        ImageView iv = inflater.inflate(R.layout.my_imageview, null);
        String imgTag = input.substring(imageIndex,endIndex);
        iv.setImageResource(-1); //or however you set your image from the tag
    
        parent.addView(tv); parent.addView(iv);
    
        input = input.substring(endIndex);
        }
    

    This should dynamically create all the imageviews you need, and parse your inputs accordingly. if you want to store the source strings in the DB, that's probably fine.

    Keeping text in textviews and images in imageviews will make your life far easier if you have to set styles/modify attributes on anything involved. Sibling views are, in general, better than hacking the wrong kind of information/too much information into one Layout element.

    BTW, i inflated custom XML layouts for imageview and textview, just in case you wanted to provide some custom style settings across all instances of them. you can just generate normal Android textviews and imageviews if those are sufficient.

    This was my initial solution that only works with a single image maximum.

    String input = //whatever
    boolean hasImage = //find image tag
    int imageBegin = //find index where image tag begins
    int imageEnd = //find index one past where image tag ends
    String leadingText = input.substring(0,imageBegin);
    String imageTag = input.substring(imageBegin, imageEnd);
    String trailingText = input.substring(imageEnd, input.length());
    
    ((TextView)findViewById(R.id.leading_textview)).setText(leadingText);
    if (hasImage){
        //use imageTag to set content of Image View)
        findViewById(R.id.image_view_id).setVisibility(View.VISIBLE);
        ((TextView)findViewById(R.id.trailing_textview)).setText(trailingText);
    }
    

    If you could have more than one image embedded, you'll have to dynamically create ImageViews and trailing TextViews, and add them to the parent of the layout in question.

提交回复
热议问题