Реализация галереи внутри моего макета

Я пытаюсь поместить в это приложение более одного изображения, которое я получил из учебника, и сделать его более похожим на Facebook, я попробовал некоторые методы, такие как UIL и другие библиотеки, но это не сработало, кто-то, пожалуйста, помогите.

Это учебная ссылка: http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/

Заранее спасибо.

РЕДАКТИРОВАТЬ: вот код

Главный

 public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://api.androidhive.info/feed/feed.json";
    public String Image;
    enter code here
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Trying to figure how to put images in the Layout here




        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    //                Snackbar.make(view, "Replace with your own action",     Snackbar.LENGTH_LONG)
    //                        .setAction("Action", null).show();
                Intent i = new Intent();
                i.setClass(getApplicationContext() , NewAdd.class);
                startActivity(i);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle actio n bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.all) {
            // Handle the camera action
        } else if (id == R.id.cars) {

        } else if (id == R.id.fur) {

        }

        DrawerLayout drawer = (DrawerLayout)     findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    }

FeedIthem Class

public class FeedItem {
private int id;
private String name, status, image, profilePic, timeStamp, url;

public FeedItem() {
}

public FeedItem(int id, String name, String image, String status,
                String profilePic, String timeStamp, String url) {
    super();
    this.id = id;
    this.name = name;
    this.image = image;
    this.status = status;
    this.profilePic = profilePic;
    this.timeStamp = timeStamp;
    this.url = url;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImge() {
    return image;
}

public void setImge(String image) {
    this.image = image;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getProfilePic() {
    return profilePic;
}

public void setProfilePic(String profilePic) {
    this.profilePic = profilePic;
}

public String getTimeStamp() {
    return timeStamp;
}

public void setTimeStamp(String timeStamp) {
    this.timeStamp = timeStamp;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
private MainActivity image;


ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
    this.activity = activity;
    this.feedItems = feedItems;
}

@Override
public int getCount() {
    return feedItems.size();
}

@Override
public Object getItem(int location) {
    return feedItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.feed_item, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();

    TextView name = (TextView) convertView.findViewById(R.id.name);
    TextView timestamp = (TextView) convertView
            .findViewById(R.id.timestamp);
    TextView statusMsg = (TextView) convertView
            .findViewById(R.id.txtStatusMsg);
    TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
    NetworkImageView profilePic = (NetworkImageView) convertView
            .findViewById(R.id.profilePic);

    final FeedImageView feedImageView = (FeedImageView) convertView
            .findViewById(R.id.feedImage1);

    final String tag = "Hello";
    feedImageView.setClickable(true);
    feedImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });


    FeedItem item = feedItems.get(position);

    name.setText(item.getName());

    // Converting timestamp into x ago format
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
            Long.parseLong(item.getTimeStamp()),
            System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
    timestamp.setText(timeAgo);

    // Chcek for empty status message
    if (!TextUtils.isEmpty(item.getStatus())) {
        statusMsg.setText(item.getStatus());
        statusMsg.setVisibility(View.VISIBLE);
    } else {
        // status is empty, remove from view
        statusMsg.setVisibility(View.GONE);
    }

    // Checking for null feed url
    if (item.getUrl() != null) {
        url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
                + item.getUrl() + "</a> "));

        // Making url clickable
        url.setMovementMethod(LinkMovementMethod.getInstance());
        url.setVisibility(View.VISIBLE);
    } else {
        // url is null, remove from the view
        url.setVisibility(View.GONE);
    }

    // user profile pic
    profilePic.setImageUrl(item.getProfilePic(), imageLoader);

    // Feed image
    if (item.getImge() != null) {

        feedImageView.setImageUrl(item.getImge(), imageLoader);
        feedImageView.setVisibility(View.VISIBLE);
        feedImageView
                .setResponseObserver(new FeedImageView.ResponseObserver() {
                    @Override
                    public void onError() {
                    }

                    @Override
                    public void onSuccess() {
                    }
                });
    } else {
        feedImageView.setVisibility(View.GONE);
    }

    return convertView;
}

Макет XML

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/feed_bg"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"

        android:layout_marginLeft="@dimen/feed_item_margin"
        android:layout_marginRight="@dimen/feed_item_margin"
        android:layout_marginTop="@dimen/feed_item_margin"
        android:background="@drawable/bg_parent_rounded_corner"
        android:orientation="vertical"
        android:paddingBottom="@dimen/feed_item_padding_top_bottom"
        android:paddingTop="@dimen/feed_item_padding_top_bottom" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingLeft="@dimen/feed_item_padding_left_right"
            android:paddingRight="@dimen/feed_item_padding_left_right" >

            <com.android.volley.toolbox.NetworkImageView
                android:id="@+id/profilePic"
                android:layout_width="@dimen/feed_item_profile_pic"
                android:layout_height="@dimen/feed_item_profile_pic"
                android:scaleType="fitCenter" >
            </com.android.volley.toolbox.NetworkImageView>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:paddingLeft="@dimen/feed_item_profile_info_padd" >

                <TextView
                    android:id="@+id/name"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textSize="@dimen/feed_item_profile_name"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/timestamp"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:textColor="@color/timestamp"
                    android:textSize="@dimen/feed_item_timestamp" />
            </LinearLayout>
        </LinearLayout>

        <TextView
            android:id="@+id/txtStatusMsg"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:paddingTop="@dimen/feed_item_status_pad_top" />

        <TextView
            android:id="@+id/txtUrl"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:linksClickable="true"
            android:paddingBottom="10dp"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:textColorLink="@color/link" />

        <info.androidhive.listviewfeed.FeedImageView
            android:id="@+id/feedImage1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:scaleType="fitXY"
            android:clickable="true"
            android:visibility="visible" />

    </LinearLayout>

</LinearLayout>

FeedImageVIew Class

public class FeedImageView extends ImageView {

public interface ResponseObserver {
    public void onError();

    public void onSuccess();
}

private ResponseObserver mObserver;

public void setResponseObserver(ResponseObserver observer) {
    mObserver = observer;
}

/**
 * The URL of the network image to load
 */
private String mUrl;

/**
 * Resource ID of the image to be used as a placeholder until the network
 * image is loaded.
 */
private int mDefaultImageId;

/**
 * Resource ID of the image to be used if the network response fails.
 */
private int mErrorImageId;

/**
 * Local copy of the ImageLoader.
 */
private ImageLoader mImageLoader;

/**
 * Current ImageContainer. (either in-flight or finished)
 */
private ImageContainer mImageContainer;

public FeedImageView(Context context) {
    this(context, null);
}

public FeedImageView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public FeedImageView(Context context, AttributeSet attrs,
                     int defStyle) {
    super(context, attrs, defStyle);
}

/**
 * Sets URL of the image that should be loaded into this view. Note that
 * calling this will immediately either set the cached image (if available)
 * or the default image specified by
 * {@link VolleyImageView#setDefaultImageResId(int)} on the view.
 *
 * NOTE: If applicable, {@link VolleyImageView#setDefaultImageResId(int)}
 * and {@link VolleyImageView#setErrorImageResId(int)} should be called
 * prior to calling this function.
 *
 * @param url
 *            The URL that should be loaded into this ImageView.
 * @param imageLoader
 *            ImageLoader that will be used to make the request.
 */
public void setImageUrl(String url, ImageLoader imageLoader) {
    mUrl = url;
    mImageLoader = imageLoader;
    // The URL has potentially changed. See if we need to load it.
    loadImageIfNecessary(false);
}

public String getmUrl()
{
    return mUrl;
}

/**
 * Sets the default image resource ID to be used for this view until the
 * attempt to load it completes.
 */
public void setDefaultImageResId(int defaultImage) {
    mDefaultImageId = defaultImage;
}

/**
 * Sets the error image resource ID to be used for this view in the event
 * that the image requested fails to load.
 */
public void setErrorImageResId(int errorImage) {
    mErrorImageId = errorImage;
}

/**
 * Loads the image for the view if it isn't already loaded.
 *
 * @param isInLayoutPass
 *            True if this was invoked from a layout pass, false otherwise.
 */
private void loadImageIfNecessary(final boolean isInLayoutPass) {
    final int width = getWidth();
    int height = getHeight();

    boolean isFullyWrapContent = getLayoutParams() != null
            && getLayoutParams().height == LayoutParams.WRAP_CONTENT
            && getLayoutParams().width == LayoutParams.WRAP_CONTENT;
    // if the view's bounds aren't known yet, and this is not a
    // wrap-content/wrap-content
    // view, hold off on loading the image.
    if (width == 0 && height == 0 && !isFullyWrapContent) {
        return;
    }

    // if the URL to be loaded in this view is empty, cancel any old
    // requests and clear the
    // currently loaded image.
    if (TextUtils.isEmpty(mUrl)) {
        if (mImageContainer != null) {
            mImageContainer.cancelRequest();
            mImageContainer = null;
        }
        setDefaultImageOrNull();
        return;
    }

    // if there was an old request in this view, check if it needs to be
    // canceled.
    if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
        if (mImageContainer.getRequestUrl().equals(mUrl)) {
            // if the request is from the same URL, return.
            return;
        } else {
            // if there is a pre-existing request, cancel it if it's
            // fetching a different URL.
            mImageContainer.cancelRequest();
            setDefaultImageOrNull();
        }
    }

    // The pre-existing content of this view didn't match the current URL.
    // Load the new image
    // from the network.
    ImageContainer newContainer = mImageLoader.get(mUrl,
            new ImageListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (mErrorImageId != 0) {
                        setImageResource(mErrorImageId);
                    }

                    if (mObserver != null) {
                        mObserver.onError();
                    }
                }

                @Override
                public void onResponse(final ImageContainer response,
                                       boolean isImmediate) {
                    // If this was an immediate response that was delivered
                    // inside of a layout
                    // pass do not set the image immediately as it will
                    // trigger a requestLayout
                    // inside of a layout. Instead, defer setting the image
                    // by posting back to
                    // the main thread.
                    if (isImmediate && isInLayoutPass) {
                        post(new Runnable() {
                            @Override
                            public void run() {
                                onResponse(response, false);
                            }
                        });
                        return;
                    }

                    int bWidth = 0, bHeight = 0;
                    if (response.getBitmap() != null) {

                        setImageBitmap(response.getBitmap());
                        bWidth = response.getBitmap().getWidth();
                        bHeight = response.getBitmap().getHeight();
                        adjustImageAspect(bWidth, bHeight);

                    } else if (mDefaultImageId != 0) {
                        setImageResource(mDefaultImageId);
                    }

                    if (mObserver != null) {
                        mObserver.onSuccess();

                    }
                }
            });

    // update the ImageContainer to be the new bitmap container.
    mImageContainer = newContainer;

}

private void setDefaultImageOrNull() {
    if (mDefaultImageId != 0) {
        setImageResource(mDefaultImageId);
    } else {
        setImageBitmap(null);
    }
}

@Override
protected void onLayout(boolean changed, int left, int top, int right,
                        int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    loadImageIfNecessary(true);
}

@Override
protected void onDetachedFromWindow() {
    if (mImageContainer != null) {
        // If the view was bound to an image request, cancel it and clear
        // out the image from the view.
        mImageContainer.cancelRequest();
        setImageBitmap(null);
        // also clear out the container so we can reload the image if
        // necessary.
        mImageContainer = null;
    }
    super.onDetachedFromWindow();
}

@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();
    invalidate();
}

/*
 * Adjusting imageview height
 * */
private void adjustImageAspect(int bWidth, int bHeight) {
    LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams();

    if (bWidth == 0 || bHeight == 0)
        return;

    int swidth = getWidth();
    int new_height = 0;
    new_height = swidth * bHeight / bWidth;
    params.width = swidth;
    params.height = new_height;
    setLayoutParams(params);
}

0 ответов

Другие вопросы по тегам