简体   繁体   English

在Android中下载后如何显示图像

[英]How to show image after downloaded in Android

I want develop android application for one site, in MainActivity i show post image and post title and i want show this datas in another Activity . 我想在MainActivity为一个站点开发android应用程序,我显示帖子图像和帖子标题,并在另一个Activity显示此数据。
I can show this datas in another activity, i send this data with putExtra in MainActivity to another Activity ! 我可以在另一个活动中显示此数据,我将MainActivity putExtra将此数据发送给另一个Activity but when use this way, first show datas (text and base image) and after a few seconds load image! 但是,当使用这种方式时,首先显示数据(文本和基础图像),然后在几秒钟后加载图像! but i want first load image (from url) then show this datas! 但我想先加载图片(从url),然后显示此数据!
MainActivity codes: MainActivity代码:

public class Main_page extends AppCompatActivity {

    private static final long RIPPLE_DURATION = 250;
    private Toolbar toolbar;
    private RelativeLayout root;
    private ImageView menu_image, toolbar_refresh;
    private RecyclerView main_recyclerView;
    private MainAdapter_loadMore mAdaper;
    private List<MainDataModel> dataModels = new ArrayList<MainDataModel>();
    protected Handler handler;
    private RelativeLayout loadLayout;
    private LinearLayoutManager mLayoutManager;
    private int pageCount = 1;
    String ServerAddress = ServerIP.getIP();
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // Initializing
        handler = new Handler();
        context = getApplicationContext();
        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        mLayoutManager = new LinearLayoutManager(this);
        loadLayout = (RelativeLayout) findViewById(R.id.main_empty_layout);
        toolbar_refresh = (ImageView) toolbar.findViewById(R.id.toolbar_update);
        // Toolbar
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle(null);
        }
        // Load First Data
        LoadData();
        // Menu
        root = (RelativeLayout) findViewById(R.id.main_root);
        View guillotineMenu = LayoutInflater.from(this).inflate(R.layout.menu_layout, null);
        root.addView(guillotineMenu);
        menu_image = (ImageView) toolbar.findViewById(R.id.toolbar_logo);
        new GuillotineAnimation.GuillotineBuilder(guillotineMenu, guillotineMenu.findViewById(R.id.menu_layout_image), menu_image)
                .setStartDelay(RIPPLE_DURATION)
                .setActionBarViewForAnimation(toolbar)
                .setClosedOnStart(true)
                .build();
        // RecyclerView and setData
        main_recyclerView = (RecyclerView) findViewById(R.id.main_recycler);
        main_recyclerView.setHasFixedSize(true);
        main_recyclerView.setLayoutManager(mLayoutManager);
        mAdaper = new MainAdapter_loadMore(this, main_recyclerView, dataModels);
        main_recyclerView.setAdapter(mAdaper);
        // Load More data
        mAdaper.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                dataModels.add(null);
                mAdaper.notifyItemInserted(dataModels.size() - 1);
                LoadMoreData(pageCount);
            }
        });

        // Refresh Data
        toolbar_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), PostShow_page.class));
            }
        });
    }

    @Subscribe
    public void onEvent(List<MainDataModel> mainInfoModels) {
        if (dataModels.size() > 0) {
            dataModels.remove(dataModels.size() - 1);
            mAdaper.notifyItemRemoved(dataModels.size());
            mAdaper.setLoaded();
        }

        mAdaper.add(mainInfoModels);
        mAdaper.notifyDataSetChanged();
        pageCount++;

        if (dataModels.isEmpty()) {
            main_recyclerView.setVisibility(View.GONE);
            loadLayout.setVisibility(View.VISIBLE);

        } else {
            main_recyclerView.setVisibility(View.VISIBLE);
            loadLayout.setVisibility(View.GONE);
        }
    }

    private void LoadData() {
        MainDataInfo dataInfo = new MainDataInfo();
        // here getMainDataInfo() should return the server response
        dataInfo.getMainDataInfo(this);
    }

    private void LoadMoreData(int pageNumber) {
        MainDataInfo_loadMore dataInfo_loadMore = new MainDataInfo_loadMore();
        // here getMainDataInfo() should return the server response
        dataInfo_loadMore.getMainDataInfo_loadMore(this, pageNumber);
    }
}

Adapter codes: 适配器代码:

public class MainAdapter_loadMore extends RecyclerView.Adapter {

    private List<MainDataModel> mDateSet;
    private Context mContext;

    private final int VIEW_ITEM = 1;
    private final int VIEW_PROG = 0;

    // The minimum amount of items to have below your current scroll position
    // before loading more.
    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private boolean loading;
    private OnLoadMoreListener onLoadMoreListener;

    public MainAdapter_loadMore(Context context, RecyclerView recyclerView, List<MainDataModel> dataSet) {
        this.mContext = context;
        this.mDateSet = dataSet;

        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {

            final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView
                    .getLayoutManager();
            recyclerView
                    .addOnScrollListener(new RecyclerView.OnScrollListener() {
                        @Override
                        public void onScrolled(RecyclerView recyclerView,
                                               int dx, int dy) {
                            super.onScrolled(recyclerView, dx, dy);
                            totalItemCount = linearLayoutManager.getItemCount();
                            lastVisibleItem = linearLayoutManager
                                    .findLastVisibleItemPosition();
                            if (!loading
                                    && totalItemCount <= (lastVisibleItem + visibleThreshold)) {
                                // End has been reached
                                // Do something
                                if (onLoadMoreListener != null) {
                                    onLoadMoreListener.onLoadMore();
                                }
                                loading = true;
                            }
                        }
                    });
        }
    }

    @Override
    public int getItemViewType(int position) {
        return mDateSet.get(position) != null ? VIEW_ITEM : VIEW_PROG;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder vh;
        if (viewType == VIEW_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.post_card_layout, parent, false);

            vh = new DataViewHolder(v);
        } else {
            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.progressbar_item, parent, false);

            vh = new ProgressViewHolder(v);
        }
        return vh;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof DataViewHolder) {
            ((DataViewHolder) holder).main_post_title.setText(Html.fromHtml(mDateSet.get(position).getTitle()));

            Glide.with(mContext)
                    .load(mDateSet.get(position).getThumbnail())
                    .placeholder(R.drawable.post_image)
                    .crossFade()
                    .into(((DataViewHolder) holder).main_post_image);

            ((DataViewHolder) holder).main_post_content.setText(Html.fromHtml(mDateSet.get(position).getContent()));

            ((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDateTime()));

            ((DataViewHolder) holder).main_author.setText(Html.fromHtml(mDateSet.get(position).getAuthor()));

            ((DataViewHolder) holder).main_category.setText(Html.fromHtml(mDateSet.get(position).getCategory()));

            ((DataViewHolder) holder).main_post_image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
                            .putExtra("title", model.getTitle())
                            .putExtra("image", model.getThumbnail())
                            .putExtra("content", model.getContent())
                            .putExtra("dateTime", model.getDateTime())
                            .putExtra("author", model.getAuthor())
                            .putExtra("category", model.getCategory()));

                }
            });

        } else {
            ((ProgressViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
        }
    }

    public void setLoaded() {
        loading = false;
    }

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

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public void remove(int position) {
        mDateSet.remove(position);
        notifyItemRemoved(position);
    }

    public void clear() {
        mDateSet.clear();
        notifyDataSetChanged();
    }


    public void add(List<MainDataModel> models) {
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public void update(List<MainDataModel> models) {
        mDateSet.clear();
        mDateSet.addAll(models);
        notifyDataSetChanged();
    }

    public class DataViewHolder extends RecyclerView.ViewHolder {

        private TextView main_post_title, main_post_content, main_dateTime, main_author, main_category;
        private ImageView main_post_image;

        public DataViewHolder(final View itemView) {
            super(itemView);

            main_post_title = (TextView) itemView.findViewById(R.id.post_content_title);
            main_post_image = (ImageView) itemView.findViewById(R.id.post_picture_image);
            main_post_content = (TextView) itemView.findViewById(R.id.post_content_text);
            main_dateTime = (TextView) itemView.findViewById(R.id.post_date_text);
            main_author = (TextView) itemView.findViewById(R.id.post_name_text);
            main_category = (TextView) itemView.findViewById(R.id.post_category_text);
        }
    }

    public static class ProgressViewHolder extends RecyclerView.ViewHolder {
        public AVLoadingIndicatorView progressBar;

        public ProgressViewHolder(View v) {
            super(v);
            progressBar = (AVLoadingIndicatorView) v.findViewById(R.id.avloadingIndicatorView);
        }
    }
}

I send with codes, **send datas to another activity : ** 我发送代码,**将数据发送到另一个活动:**

int pos = holder.getPosition();
                    MainDataModel model = mDateSet.get(pos);
                    v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
                            .putExtra("title", model.getTitle())
                            .putExtra("image", model.getThumbnail())
                            .putExtra("content", model.getContent())
                            .putExtra("dateTime", model.getDateTime())
                            .putExtra("author", model.getAuthor())
                            .putExtra("category", model.getCategory()));

AsyncTask code (MainActivity) : AsyncTask代码(MainActivity):

public class MainDataInfo {
    private Context mContext;
    private String ServerAddress = ServerIP.getIP();

    public void getMainDataInfo(Context context) {
        mContext = context;
        new getInfo().execute(ServerAddress + "page=1");
    }

    private class getInfo extends AsyncTask<String, Void, String> {
        EventBus bus = EventBus.getDefault();
        private String ou_response;
        private List<MainDataModel> infoModels;

        @Override
        protected void onPreExecute() {
            CustomProcessDialog.createAndShow(mContext);
            infoModels = new ArrayList<>();
        }

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();

            //String url = (String) params[0];
            Request request = new Request.Builder()
                    .url(ServerAddress + "page=1")
                    .cacheControl(CacheControl.FORCE_NETWORK)
                    .build();

            Response response;
            try {
                response = client.newCall(request).execute();
                ou_response = response.body().string();
                response.body().close();
                if (ou_response != null) {
                    try {
                        JSONObject postObj = new JSONObject(ou_response);
                        JSONArray postsArray = postObj.optJSONArray("posts");
                        infoModels = new ArrayList<>();

                        for (int i = 0; i <= infoModels.size(); i++) {
                            JSONObject postObject = (JSONObject) postsArray.get(i);
                            // Thumbnail
                            JSONObject images = postObject.optJSONObject("thumbnail_images");
                            JSONObject imagesPair = images.optJSONObject("medium");
                            // Author
                            JSONObject Author = postObject.optJSONObject("author");
                            // Category
                            JSONArray category = postObject.getJSONArray("categories");
                            for (int j = 0; j < category.length(); j++) {
                                JSONObject categoryObject = category.getJSONObject(j);

                                int id = postObject.getInt("id");
                                String title = postObject.getString("title");
                                String content = postObject.getString("content");
                                String dateTime = postObject.getString("date");
                                String thumbnail = imagesPair.getString("url");
                                String authorShow = Author.getString("name");
                                String categoryShow = categoryObject.getString("title");

                                Log.d("Data", "Post id: " + id);
                                Log.d("Data", "Post title: " + title);
                                Log.d("Data", "Post image: " + thumbnail);
                                Log.d("Data", "Post author: " + authorShow);
                                Log.d("Data", "Post category: " + categoryShow);
                                Log.d("Data", "---------------------------------");

                                //Use the title and id as per your requirement
                                infoModels.add(new MainDataModel(id, title, content, dateTime, authorShow, categoryShow, thumbnail));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ou_response;
        }

        @Override
        protected void onPostExecute(String result) {
            CustomProcessDialog.dissmis();
            if (result != null) {
                bus.post(infoModels);
            } else {
                Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Another Activity codes: 另一个活动代码:

public class PostShow_page extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener {

    private static final float PERCENTAGE_TO_SHOW_TITLE_AT_TOOLBAR = 0.9f;
    private static final float PERCENTAGE_TO_HIDE_TITLE_DETAILS = 0.3f;
    private static final int ALPHA_ANIMATIONS_DURATION = 500;

    private boolean mIsTheTitleVisible = false;
    private boolean mIsTheTitleContainerVisible = true;

    private LinearLayout mTitleContainer;
    private TextView mTitle;
    private AppBarLayout mAppBarLayout;
    private Toolbar mToolbar;

    private TextView postShow_title, postShow_title2, postShow_content, postShow_dateTime,
            postShow_author, postShow_category;
    private ImageView post_cover;

    private String title = "", image = "", content = "", dateTime = "", author = "", category = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_show_page);

        bindActivity();

        mAppBarLayout.addOnOffsetChangedListener(this);

        mToolbar.inflateMenu(R.menu.post_menu);
        startAlphaAnimation(mTitle, 0, View.INVISIBLE);

        post_cover = (ImageView) findViewById(R.id.postShow_cover_image);
        postShow_title = (TextView) findViewById(R.id.postShow_title);
        postShow_title2 = (TextView) findViewById(R.id.postShow_titleBig);
        postShow_content = (TextView) findViewById(R.id.postShow_content_text);
        postShow_dateTime = (TextView) findViewById(R.id.postShow_man_date_text);
        postShow_author = (TextView) findViewById(R.id.postShow_man_author_text);
        postShow_category = (TextView) findViewById(R.id.postShow_man_category_text);

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            title = bundle.getString("title");
            image = bundle.getString("image");
            content = bundle.getString("content");
            dateTime = bundle.getString("dateTime");
            author = bundle.getString("author");
            category = bundle.getString("category");
        }
        if (title != null) {
            postShow_title.setText(title);
            postShow_title2.setText(title);
        }
        if (image != null) {
            Glide.with(this)
                    .load(image)
                    .placeholder(R.drawable.post_image)
                    .into(post_cover);
        }
        if (content != null) {
            postShow_content.setText(Html.fromHtml(content));
        }
        if (dateTime != null) {
            postShow_dateTime.setText(dateTime);
        }
        if (author != null) {
            postShow_author.setText(author);
        }
        if (category != null) {
            postShow_category.setText(category);
        }

    }

How can i first downlaod image then show datas in PostShow_page ? 我如何首先下载图像然后在 PostShow_page 显示数据

Attention : Please don't give me negative points, I search in google but not find answer to my question. 注意:请不要给我负面点,我在google中搜索但找不到我的问题的答案。 I am amateur and I really need you helps! 我是业余爱好者,我真的需要您的帮助! thanks all <3 谢谢所有<3

As you are using Glide to load image into imageview, you can do it in following way in order to achieve your desired functionality. 当您使用Glide将图像加载到imageview时,可以按照以下方式进行操作,以实现所需的功能。 Add your show data code in onResourceReady() method onResourceReady()方法中添加显示数据代码

ProgressDialog progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.show();
if (image != null) { 
   Glide.with(this)
        .load(image)
        .placeholder(R.drawable.post_image)
        .listener(new RequestListener<String, GlideDrawable>() {
                         @Override
                         public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                             return false;
                         }

                         @Override
                         public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            progressDialog.dismiss();
                             return false;
                         }
                     })
       .into(post_cover);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM