使用来自网址的图片折叠工具栏?

时间:2015-12-02 15:54:34

标签: android android-asynctask material-design toolbar android-collapsingtoolbarlayout

我为我的Android应用程序做了一个带有图像的折叠工具栏。它与drawable图像完美配合。我的问题是当我从URL检索图像并将其分配给同一图像视图时。折叠工具栏无法使用。标题消失了,无法滚动,也没有图像。

这是我的截图。

Image from drawable After set image from async task

图片1是来自drawable和的图片 图2是从URL

中检索的图像

活动:

    import android.app.ProgressDialog;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.drawable.BitmapDrawable;
    import android.os.AsyncTask;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.design.widget.CollapsingToolbarLayout;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.graphics.Palette;
    import android.support.v7.widget.Toolbar;
    import android.widget.ImageView;

    import android.widget.Toast;

    import java.io.InputStream;
    import java.net.URL;


    public class RecipeDisplay extends AppCompatActivity {
        CollapsingToolbarLayout collapsingToolbarLayout;
        ImageView image;
        ImageView img;
        Bitmap bitmap;
        ProgressDialog pDialog;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recipe_display);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            //default header image for toolbar
            image = (ImageView) findViewById(R.id.image);
            image.setImageResource(R.drawable.header);

            //Loading image using async task
            new LoadImage().execute("http://www.twinaccommodation.com/media/313799/pub_food_281x281.jpg");

            collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    collapsingToolbarLayout.setTitle("Collapsing");
    collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));

       }

       //async task
       private class LoadImage extends AsyncTask<String, String, Bitmap> {
            @Override
            protected void onPreExecute() {
               super.onPreExecute();
               pDialog = new ProgressDialog(RecipeDisplay.this);
               pDialog.setMessage("Loading....");
               pDialog.show();

            }

            protected Bitmap doInBackground(String... args) {
                try {
                    bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            protected void onPostExecute(Bitmap img) {

                if (img != null) {
                    image.setImageBitmap(img);
                    pDialog.dismiss();

                } else {

                    pDialog.dismiss();
                    Toast.makeText(RecipeDisplay.this, "Error retrieving image", Toast.LENGTH_SHORT).show();

                }
            }
        }

    }

LOGCAT也没有引发错误......请帮帮我。

编辑:XML布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleMarginEnd="64dp"
        android:fitsSystemWindows="true">

        <ImageView
            android:id="@+id/image"
            android:src="@drawable/pic"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            android:fitsSystemWindows="true"
            app:layout_collapseMode="parallax"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_collapseMode="pin" />

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        app:cardElevation="6dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="30dp"
                android:text="Lorem Ipsum..."
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    app:layout_anchor="@id/app_bar_layout"
    style="@style/fab"
    app:theme="@style/ThemeOverlay.AppCompat.Light"
    app:layout_anchorGravity="bottom|right|end" />

3 个答案:

答案 0 :(得分:9)

使用android studio 1.5及更高版本,您可以创建滚动模板。 然后将imageview添加到布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.codephillip.app.MyActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:fitsSystemWindows="true"
        android:layout_height="@dimen/app_bar_height"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbar_layout"
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

            <ImageView
                android:id="@+id/image_id"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/placeholder_image"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_height="?attr/actionBarSize"
                android:layout_width="match_parent"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_stretch_detail"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:layout_anchor="@id/app_bar"
        app:layout_anchorGravity="bottom|end"
        android:src="@drawable/ic_share_white_24dp"/>
</android.support.design.widget.CoordinatorLayout>

然后使用毕加索将其加载到图像中

public class MyActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ImageView toolbarImage = (ImageView) findViewById(R.id.image_id);

        String url = "" //place your url here
        picassoLoader(this, toolbarImage, url);
     }

        public void picassoLoader(Context context, ImageView imageView, String url){
        Log.d("PICASSO", "loading image");
        Picasso.with(context)
                .load(url)
                        //.resize(30,30)
                .placeholder(R.drawable.placeholder_image)
                .error(R.drawable.placeholder_image)
                .into(imageView);
    }
}

将picasso库添加到gradle依赖项中

compile 'com.squareup.picasso:picasso:2.5.2'

答案 1 :(得分:3)

我认为你的问题在于,虽然你没有为你的图像视图提供任何绘图,但是视图加载的初始高度为0dp,因为你在高度参数中给出了wrap_content。现在,即使图像被加载到图像视图中,因为视图没有被无效,所以它仍然具有0dp高度。所以你没有看到图像。

解决方案你可以尝试:

1)为您的图片视图提供height的初始200dp,它会像魅力一样。

2)如果你想使用height作为wrap_content,你也可以使视图无效(意味着在屏幕上用新参数再次绘制它),试试这个:imageView.invalidate();。 在此块中输入以下内容:

 protected void onPostExecute(Bitmap img) {

            if (img != null) {
                image.setImageBitmap(img);
                pDialog.dismiss();
                image.invalidate();

            } else {

                pDialog.dismiss();
                Toast.makeText(RecipeDisplay.this, "Error retrieving image", Toast.LENGTH_SHORT).show();

            }
        }

答案 2 :(得分:1)

使用Picasso库并使用此库从.jqGrid("navGrid", pagerIdSelector, {add: false, edit: false, refreshstate: "current"}) .jqGrid("inlineNav", pagerIdSelector, { editParams: editOptions, addParams: {addRowParams: editOptions}}) .jqGrid("navButtonAdd", pagerIdSelector, { caption: "", title: "Copy selected row", id: $grid[0].id + "_ilcopy", buttonicon: "ui-icon-copy", onClickButton: function () { var $self = $(this), p = $self.jqGrid("getGridParam"), rowData, srcrowid = p.selrow, savedRows = p.savedRow; if (srcrowid !== null) { if (savedRows.length > 0) { // cancel editing $self.jqGrid("restoreRow", savedRows[0].id); } rowData = $self.jqGrid("getRowData", srcrowid); rowData.id = ""; rowData.Catalogue = ""; rowData.copyID = srcrowid; $self.jqGrid("addRow", { initdata: rowData, addRowParams: editOptions }); } else { alert("Please select a row to copy"); return false; } } });

获取位图
AsyncTask

然后在Bitmap image = Picasso.with(getAppilicationContext()).load(YourString).get(); 将图片设置为onPostExecute

或使用此AsyncTask

collapsingToolbar

开始执行任务:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mIcon;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
}