无法在文本视图的html.fromhtml()中显示动态图像

gblwokeq  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(291)

我正在androidstudio中开发一个应用程序,其中的内容来自recyclerview中的api。在api中有一个元素“content”,它发送所有html标记和图像,就像一个完整的页面。我必须在文本视图中显示该页。我尝试过htm.fromhtml方法,但它不显示图像。我已经搜索了所有的答案并得到了imagegetter方法的解决方案,但是我无法在imagegetter的recycleradapter中显示动态内容。我必须保持在我的应用程序可绘制的图像,并匹配正在解析的源url。请帮忙。下面是我的代码。
页面活动.java

public class PageActivity extends AppCompatActivity {
    RequestQueue queue;
    String menuidpage;

    RecyclerView recyclerView;
    List<MenuFeeds> feedsList = new ArrayList<MenuFeeds>();
    String newimage = "http://www.groveus.com/micro/assets/uploads/page/";
    PageRecyclerAdapter adapter;
    private ProgressDialog pDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_page);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    Bundle bundle=getIntent().getExtras();
    menuidpage=bundle.getString("page_id");

    recyclerView = (RecyclerView) findViewById(R.id.recyclerviewpage);
    pDialog = new ProgressDialog(this);
    adapter = new PageRecyclerAdapter(this, feedsList);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    recyclerView.setAdapter(adapter);
    //Getting Instance of Volley Request Queue
    queue = NetworkController.getInstance(this).getRequestQueue();
    //Volley's inbuilt class to make Json array request

    pDialog.setMessage("Loding...");
    pDialog.show();
    String url = "http://www.groveus.com/micro/api/index.php/pages/view? 
    id="+menuidpage;

    JsonArrayRequest menuReq = new JsonArrayRequest(url, new 
    Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            pDialog.dismiss();

            for (int i = 0; i < response.length(); i++) {
                try {

                    JSONObject obj = response.getJSONObject(i);
                    MenuFeeds feeds = new MenuFeeds(obj.getInt("page_id"), 
   obj.getString("status"), obj.getString("title"), 
   newimage+obj.getString("image"),obj.getString("content"));

                    // adding movie to movies array
                    feedsList.add(feeds);

                } catch (Exception e) {
                    System.out.println(e.getMessage());
                } finally {
                    //Notify adapter about data changes
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error.getMessage());
            pDialog.dismiss();

        }
    });
    //Adding JsonArrayRequest to Request Queue
    queue.add(menuReq);
}

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;

    }
}

pagerecycleradapter.java页

public class PageRecyclerAdapter extends 
RecyclerView.Adapter<PageRecyclerAdapter.MyViewHolder> implements 
View.OnTouchListener
    {

private List<MenuFeeds> feedsList;
private Context context;
private LayoutInflater inflater;

public PageRecyclerAdapter(Context context, List<MenuFeeds> feedsList) {

    this.context = context;
    this.feedsList = feedsList;
    inflater = (LayoutInflater) 
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View rootView = inflater.inflate(R.layout.list_layout5, parent, false);
    return new MyViewHolder(rootView);
    }

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final MenuFeeds feeds = feedsList.get(position);
    //Pass the values of feeds object to Views
    //holder.idmenu.setText(feeds.getMenuId());
    //holder.title.setText(feeds.getFeedName());
   /* holder.description.setText(Html.fromHtml(feeds.getDescription(), 0, 
new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String s) {
            int id;

            if 
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT 
INFECTION 1.png")) {
                id = R.drawable.urin1;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/URINARY TRACT 
INFECTION 2.png")) {
                id = R.drawable.urin2;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE 
INFECTION 1.png")) {
                id = R.drawable.skinsoft1;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/SKIN AND SOFT TISSUE 
INFECTION 2.png")) {
                id = R.drawable.skinsoft2;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/RESPIRATORY TRACT 
INFECTION.png")) {
                id = R.drawable.respo;
            }
            else if (s.equals("http://groveus.com/micro/assets/images/LOCAL 
BACTERIAL INFECTIONS.png")) {
                id = R.drawable.local;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION 
2nd 1.png")) {
                id = R.drawable.urine2nd1;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/URINARY TRACT INFECTION 
2nd 2.png")) {
                id = R.drawable.urine2nd2;
            }
            else if 
(s.equals("http://groveus.com/micro/assets/images/table.png")) {
                id = R.drawable.table;
            }
            else if 
(s.equals("http://www.groveus.com/micro/assets/images/table 2.png")) {
                id = R.drawable.table2;
            }
            else {
                return null;
            }

            Drawable d = context.getResources().getDrawable(id);
            d.setBounds(0,0,1020,600);
            return d;
        }
    }, null));*/

    holder.description.setText(Html.fromHtml(feeds.getDescription()));

    holder.description.setOnTouchListener(this);
    holder.description.setMovementMethod(new ScrollingMovementMethod());
    holder.imageview.setImageUrl(feeds.getImgURL(), 
    NetworkController.getInstance(context).getImageLoader());
    // holder.ratingbar.setProgress(feeds.getRating());

    }

@Override
public int getItemCount() {
    return feedsList.size();
    }

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }

        public class MyViewHolder extends RecyclerView.ViewHolder {

private TextView title,description;
private NetworkImageView imageview;
//private ProgressBar ratingbar;

public MyViewHolder(View itemView) {
    super(itemView);
    title = (TextView) itemView.findViewById(R.id.ImageNameTextView);

    description = (TextView) itemView.findViewById(R.id.desc);
    //idmenu = (TextView) itemView.findViewById(R.id.ImageNameTextView2);
    UrlImageParser p=new UrlImageParser(description,context);
    // Volley's NetworkImageView which will load Image from URL
    imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);

        }
    }         
}

菜单种子.java

public class MenuFeeds
{
   private String  imgURL, feedName, description,page;
    //private String id;
   private int id;

public MenuFeeds(int menuid, String page, String name, String imgurl,String 
desc) {
    this.id=menuid;
    this.page=page;
    this.feedName = name;
    this.imgURL = imgurl;
    this.description = desc;
    //this.rating = rating;
    }

    public int getMenuId() {
    return id;
    }

    public String getPageID()
    {
        return page;
    }

    public String getDescription() {
        return description;
   }

    public String getImgURL() {
        return imgURL;
    }

    public String getFeedName() {
        return feedName;
    }
}
xqk2d5yq

xqk2d5yq1#

试试这个
使用piccaso加载图像
在build.gradle中添加以下库

implementation 'com.squareup.picasso:picasso:2.71828'

当您需要设置图像时,请使用piccaso这种方式

Picasso.get()
.load(your_image)
.placeholder(R.drawable.user_placeholder)
.error(R.drawable.your_error_image_or_blank)
.into(your_imageView);
ukdjmx9f

ukdjmx9f2#

我在一个月前也遇到过类似的问题,使用了这个方法,效果很好:

String htmlData = listData.get(position).getValue();
               String showData = htmlData.replace("\n", "");

                URLImageParser p = new URLImageParser(holder.textt, context);
                Spanned htmlAsSpanned = Html.fromHtml(showData,p,null);

                holder.yourTextView.setText(htmlAsSpanned);

现在复制并粘贴这两种方法:
第一种方法:

public class URLDrawable extends BitmapDrawable {
    protected Drawable drawable;
     @Override
    public void draw(Canvas canvas) {
        if(drawable != null) {
            drawable.draw(canvas);
        }
    }
}

///第二种方法:

public class URLImageParser implements Html.ImageGetter {
    Context c;
    TextView container;

    /***
     * Construct the URLImageParser which will execute AsyncTask and refresh the container
     * @param t
     * @param c
     */
    public URLImageParser(TextView t, Context c) {
        this.c = c;

        this.container = t;
    }

    public Drawable getDrawable(String source) {
        URLDrawable urlDrawable = new URLDrawable();

        // get the actual source
        ImageGetterAsyncTask asyncTask =
                new ImageGetterAsyncTask( urlDrawable);

        asyncTask.execute(source);

        // return reference to URLDrawable where I will change with actual image from
        // the src tag
        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable d) {
            this.urlDrawable = d;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String source = params[0];
            return fetchDrawable(source);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            // set the correct bound according to the result from HTTP call
            urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
                    + result.getIntrinsicHeight());

            // change the reference of the current drawable to the result
            // from the HTTP call
            urlDrawable.drawable = result;

            // redraw the image by invalidating the container
            URLImageParser.this.container.invalidate();
            URLImageParser.this.container.setHeight((URLImageParser.this.container.getHeight()
                    + result.getIntrinsicHeight()));

        }

        /***
         * Get the Drawable from URL
         * @param urlString
         * @return
         */
        public Drawable fetchDrawable(String urlString) {
            try {
                InputStream is = fetch(urlString);
                Drawable drawable = Drawable.createFromStream(is, "src");
                drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
                        + drawable.getIntrinsicHeight());
                return drawable;
            } `enter code here`catch (Exception e) {
                return null;
            }
        }

        private InputStream fetch(String urlString) throws MalformedURLException, IOException {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(urlString);
            HttpResponse response = httpClient.execute(request);
            return response.getEntity().getContent();
        }
    }
}

相关问题