如何在android中使用volly将单个图像从服务器放入我的imageview?

时间:2017-01-12 06:02:31

标签: android networkimageview

enter image description here enter image description here

我已经阅读了很多关于从服务器获取图像并将其放入listview之类的内容,但是这里的活动我需要从服务中获得单个图像,这应该完全适合所有设备。我可以这样做吗?我是android新手,所以不太了解那个......很有帮助吗?如果能给出任何一个例子,那将是非常有帮助的。

这是我的MainActivity.class:

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;

import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.android.volley.Request;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentOne.OnFragmentInteractionListener,
        FragmentTwo.OnFragmentInteractionListener

{
    ImageView im1, im2, im3;
    ImageLoader mImageLoader;
    ImageView mImageView;
    // The URL for the image that is being loaded.
    private static final String IMAGE_URL =
            "http://developer.android.com/images/training/system-ui.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        im1 = (NetworkImageView) findViewById(R.id.ms1);


        ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(final Bitmap response) {
                im1.setImageBitmap(response);
            }
        }, 0, 0, ImageView.ScaleType.CENTER_INSIDE, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(imageRequest);

        if (savedInstanceState == null) {
            Fragment fragment = null;
            Class fragmentClass = null;
            fragmentClass = FragmentOne.class;
            try {
                fragment = (Fragment) fragmentClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }

            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        }
        im1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(MainActivity.this, Login.class));
            }
        });
        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.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // User chose the "Settings" item, show the app settings UI...


            case R.id.action_cart:


                Intent ibs = new Intent(MainActivity.this,AddToCart.class);
                ibs.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(ibs);
                finish();
                break;
            // User chose the "Favorite" action, mark the current item
            // as a favorite...


            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
        return true;
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment = null;
        Class fragmentClass = null;
        if (id == R.id.br_menu) {
            Intent i = new Intent(MainActivity.this,Login.class);
            startActivity(i);

        } else if (id == R.id.tr_ordr) {
            fragmentClass = FragmentTwo.class;
        } else if (id == R.id.pl_ordr) {
            fragmentClass = FragmentOne.class;
        } else if (id == R.id.profl) {
            fragmentClass = FragmentTwo.class;
        } else if (id == R.id.addr) {
            fragmentClass = FragmentOne.class;
        } else if (id == R.id.crds) {
            fragmentClass = FragmentTwo.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //FragmentManager fragmentManager = getSupportFragmentManager();
       //fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

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

    @Override
    public void onFragmentInteraction(Uri uri) {

    }




}

对于m1,我需要设置imageview ...

3 个答案:

答案 0 :(得分:0)

使用ImageRequest的{​​{1}}从Volley下载图片并在URL上使用。

ImageView

答案 1 :(得分:0)

始终使用某些第三方库来加载Glide,fresco,picasso等图片。

为什么?
 1.当加载许多图像时,例如列表视图,以防止我的内存不足内存错误  2.用于禁食图像
 3.将来使用它。这些图像存储在缓存中,您可以在将来使用它们而无需再次实际下载它们。这有助于节省数据并减少用户的等待时间。

答案 2 :(得分:0)

检查volley networkimageview并使用LruCache。你可以找到所有here。只需使用LruCache。它非常简单而有力。我一直在使用很多项目。

实施此步骤的步骤

  1. 创建类LruBitmapCache并下载文件然后复制代码

      

    https://drive.google.com/file/d/0B8oLTPOweId6cnFBamhFd3pva2c/view?usp=sharing

  2. 创建一个名为AppController的应用程序类,并从下面的文件中复制代码

    https://drive.google.com/file/d/0B8oLTPOweId6T1VEdlVTeWwxUTQ/view?usp=sharing

  3. xml中的
  4. 包含此视图以代替imageview

    <com.android.volley.toolbox.NetworkImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp">
    
  5. 活动

    NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
    
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    
    thumbNail.setImageUrl(url, imageLoader);