在ListView中从ImageButton创建新活动

时间:2016-03-17 20:39:31

标签: java android listview android-imagebutton

我是初学者并尝试在应用上工作。我想在点击imageButton上的listView时创建新的网页/活动。 (图像从网址抓取)。任何帮助表示赞赏。

以下是main.java

public class IngredientCategoryMain extends Activity {

ListView list;
String[] title;
CategoryImageAdapter adapter;



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

    list=(ListView)findViewById(R.id.listView);
    title = getResources().getStringArray(R.array.titles);
    adapter=new CategoryImageAdapter(this, mStrings, title);
    list.setAdapter(adapter);

}

@Override
public void onDestroy() {
    list.setAdapter(null);
    super.onDestroy();
}

public View.OnClickListener listener=new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        adapter.imageLoader.clearCache();
        adapter.notifyDataSetChanged();


    }
};

public void onItemClick(int mPosition) {
    String tempValues = title[mPosition];
    Toast.makeText(IngredientCategoryMain.this, "You have clicked "+tempValues, Toast.LENGTH_LONG).show();
}

private String[] mStrings={
        "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Ic_cake_48px.svg/2000px-Ic_cake_48px.svg.png",
        "https://pixabay.com/static/uploads/photo/2013/04/01/21/30/can-99137_960_720.png",
        "http://publicdomainvectors.org/photos/Gerald_G_Fast_Food_Drinks_(FF_Menu)_9.png",
        "https://pixabay.com/static/uploads/photo/2014/03/25/16/59/apple-297775_960_720.png",
        "https://pixabay.com/static/uploads/photo/2012/04/16/11/14/mortar-35544_960_720.png",
        "https://pixabay.com/static/uploads/photo/2013/07/13/10/05/cattle-156498_960_720.png",
        "https://pixabay.com/static/uploads/photo/2013/07/12/15/39/acorn-150258_960_720.png",
        "http://publicdomainvectors.org/photos/johnny_automatic_bread_with_knife.png",
        "https://pixabay.com/static/uploads/photo/2015/09/13/00/12/chicken-937584_960_720.jpg",
        "http://publicdomainvectors.org/photos/bowl-of-steaming-soup-01.png",
        "https://pixabay.com/static/uploads/photo/2014/04/02/10/38/fish-304097_960_720.png",
        "http://publicdomainvectors.org/photos/Erbsen-lineart.png"
};

}

适配器

public class CategoryImageAdapter extends BaseAdapter implements OnClickListener {

private Activity activity;
private String[] data;
private String[] title;


private static LayoutInflater inflater = null;
public ImageLoader imageLoader;


public CategoryImageAdapter(Activity a, String[] d, String[] t) {
    activity = a;
    title = t;
    data = d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoader = new ImageLoader(activity.getApplicationContext());


}


@Override
public int getCount() {
    return title.length;
}

@Override
public Object getItem(int position) {
    return position;
}

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

@Override
public void onClick(View v) {

}


public static class ViewHolder {

    public ImageButton imageButton;
    public TextView textView;
}


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


    View vi = convertView;
    ViewHolder holder;
    if (convertView == null) {
        vi = inflater.inflate(R.layout.ingcategoryrow, null);
        holder = new ViewHolder();
        holder.textView = (TextView) vi.findViewById(R.id.textView2);
        holder.imageButton = (ImageButton) vi.findViewById(R.id.imageButton2);
        vi.setTag(holder);
    } else
        holder = (ViewHolder) vi.getTag();


    holder.textView.setText(title[position]);
    ImageButton imageButton = holder.imageButton;
    imageLoader.DisplayImage(data[position], imageButton);
    vi.setOnClickListener(new OnItemClickListener(position));
    return vi;
}



private class OnItemClickListener implements OnClickListener{
    private int mPosition;

    OnItemClickListener(int position) {
        mPosition = position;
    }


    @Override
    public void onClick(View arg0) {
        IngredientCategoryMain sct = (IngredientCategoryMain)activity;
        sct.onItemClick(mPosition);

      }
    }

ImageLoader的

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageButton, String> imageButtons = Collections.synchronizedMap(new WeakHashMap<ImageButton, String>());
ExecutorService executorService;
Handler handler = new Handler();

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService= Executors.newFixedThreadPool(5);

}

final int stub_id=R.drawable.bakingood;

public void DisplayImage(String url, ImageButton imageButton) {
    imageButtons.put(imageButton, url);

    Bitmap bitmap = memoryCache.get(url);

    if(bitmap!=null) {
        imageButton.setImageBitmap(bitmap);
    } else {
        queuePhoto(url, imageButton);
        imageButton.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageButton imageButton){
    PhotoToLoad p = new PhotoToLoad(url, imageButton);
    executorService.submit(new PhotosLoader(p));

}

private class PhotoToLoad {
    public String url;
    public ImageButton imageButton;

    public PhotoToLoad(String u, ImageButton i) {
        url=u;
        imageButton=i;

    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {

        this.photoToLoad=photoToLoad;
    }

    @Override
    public void run() {
        try{
            if(imageButtonReused(photoToLoad))
                return;

            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageButtonReused(photoToLoad))
                return;

            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            handler.post(bd);

        } catch (Throwable th) {
            th.printStackTrace();
        }
      }
    }

private  Bitmap getBitmap(String url) {
    File f=fileCache.getFile(url);
    Bitmap b= decodeFile(f);
    if(b!=null)
        return  b;

    try {
        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        conn.disconnect();
        bitmap = decodeFile(f);

        return bitmap;

    } catch (Throwable ex) {
        ex.printStackTrace();
        if(ex instanceof  OutOfMemoryError)
            memoryCache.clear();
        return null;
      }

    }


private Bitmap decodeFile(File f) {
    try {

        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        FileInputStream stream1=new FileInputStream(f);
        BitmapFactory.decodeStream(stream1,null,o);
        stream1.close();

        //Find the correct scale value. It should be the power of 2.

        // Set width/height of recreated image
        final int REQUIRED_SIZE=85;

        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with current scale values
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        FileInputStream stream2=new FileInputStream(f);
        Bitmap bitmap= BitmapFactory.decodeStream(stream2, null, o2);
        stream2.close();
        return bitmap;

    } catch (FileNotFoundException e) {
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

boolean imageButtonReused(PhotoToLoad photoToLoad){
    String tag=imageButtons.get(photoToLoad.imageButton);
    if (tag==null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {bitmap = b;photoToLoad = p;}

    public void run() {
        if (imageButtonReused(photoToLoad))
            return;
        if (bitmap!=null)
            photoToLoad.imageButton.setImageBitmap(bitmap);
        else
            photoToLoad.imageButton.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
  }
}

的MemoryCache

public class MemoryCache {

private static final String TAG = "MemoryCache";

private Map<String, Bitmap> cache = Collections.synchronizedMap(
        new LinkedHashMap<String, Bitmap>(10,1.5f, true));

private long size=0;
private long limit=1000000;

public MemoryCache () {
    setLimit(Runtime.getRuntime().maxMemory() / 4);
}

public void setLimit(long limit) {
    this.limit = limit;
    Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");

}

public Bitmap get(String id) {
    try {
        if (!cache.containsKey(id))
            return null;
        return cache.get(id);
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        return null;
      }
    }

public void put(String id, Bitmap bitmap) {
    try{
        if(cache.containsKey(id))
            size-=getSizeInBytes(cache.get(id));
        cache.put(id, bitmap);
        size+=getSizeInBytes(bitmap);
        checkSize();
    }catch (Throwable th) {
        th.printStackTrace();
      }
    }

private void checkSize() {
    Log.i(TAG, "cache size="+size+" length="+cache.size());
    if(size>limit) {
        Iterator<Map.Entry<String, Bitmap>> iter=cache.entrySet().iterator();

        while (iter.hasNext()) {
            Map.Entry<String, Bitmap> entry=iter.next();
            size-=getSizeInBytes(entry.getValue());
            iter.remove();
            if(size<=limit)
                break;
            }
            Log.i(TAG, "Clean cache.New size "+cache.size());
        }
    }

public void clear() {
    try{
        cache.clear();
        size=0;
    }catch (NullPointerException ex) {

      }
    }

private long getSizeInBytes(Bitmap bitmap) {
    if (bitmap==null)
        return 0;
    return bitmap.getRowBytes()*bitmap.getHeight();
  }

}

FileCache

public class FileCache {
private File cacheDir;
public FileCache(Context context) {
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED))
    {
        //if SDCARD is mounted (SDCARD is present on device and mounted)
        cacheDir = new File(
                android.os.Environment.getExternalStorageDirectory(),"LazyList");
    }
    else
    {
        // if checking on simulator the create cache dir in your application context
        cacheDir=context.getCacheDir();
    }

    if(!cacheDir.exists()){
        // create cache dir in your application context
        cacheDir.mkdirs();
      }
    }


public void clear() {
    File[] files=cacheDir.listFiles();
    if(files==null)
        return;
    for (File f:files)
        f.delete();
    }

public File getFile(String url) {
    //Identify images by hashcode or encode by URLEncoder.encode.
    String filename=String.valueOf(url.hashCode());

    File f = new File(cacheDir, filename);
    return f;
  }
}

的Utils

public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
    final int buffer_size=1024;
    try {
        byte[] bytes=new byte[buffer_size];
        for(;;) {
            int count = is.read(bytes, 0, buffer_size);
            if (count == -1)
                break;
            os.write(bytes, 0, count);
        }

    }
    catch (IOException e) {
        e.printStackTrace();
    }
  }
}

3 个答案:

答案 0 :(得分:0)

在listitem.onclick中添加'startActivity(intent)'的代码 - 您可以查看正在点击的图片或位置,然后启动相应的活动。

答案 1 :(得分:0)

在适配器中,在此行之后:

std::shared_ptr<Tony>
Movie::addTony()
{
  auto tony = std::make_shared<Tony>();
  attachActor(tony);
  return tony;
}

做这样的事情:

ImageButton imageButton = holder.imageButton;

它的工作方式是每个视图都有一个选项来响应用户“在他身上”执行的点击事件,你需要做的就是将View.OnClickListener接口的实现传递给View(通过setOnClickListener方法)就是这样。 第二步是启动一个非常简单的活动,你需要使用当前上下文和你想要启动的活动的类创建一个intent,然后从当前上下文中调用startActivity方法。

在这种情况下,当前上下文由活动参考表示。

答案 2 :(得分:0)

这一行之后

ImageButton imageButton = holder.imageButton; 

只需添加以下代码行

imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.startActivity(new Intent(activity, YourActivityClass.class));
            }
});