简体   繁体   English

在ListView中从ImageButton创建新活动

[英]Create new activity from ImageButton in ListView

Im beginner and try to work on an app. 我是初学者,并尝试在应用程序上工作。 I want to create a new page/activity when the imageButton on the listView is clicked. 单击listView上的imageButton时,我想创建一个新页面/活动。 (The image is grab from url). (图像从网址抓取)。 Any help is appreciated. 任何帮助表示赞赏。

Here is the main.java 这是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"
};

}

Adapter 适配器

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 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 的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 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 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();
    }
  }
}

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

In your adapter, after this line: 在您的适配器中,此行之后:

ImageButton imageButton = holder.imageButton;

do something like this: 做这样的事情:

imageButton.setOnClickListener(new.View.OnClickListener(){
@Override
Public void onClick(View :)
{
    Intent intent = New intent(activity,     ExampleActivityName.class);
    activity.startActivity(intent);

}

});

The way it works is that every view has an option to react to click events that the user performs ”on him”, all you need to do is to pass an implementation of the View.OnClickListener Interface to the View (via the setOnClickListener method) and that's it. 它的工作方式是每个视图都有一个选项来响应用户“在他身上”执行的点击事件,你需要做的就是将View.OnClickListener接口的实现传递给View(通过setOnClickListener方法)就是这样。 Second step is to start an activity which is faily easy, you need to create an intent with the current context and the class of the activity you wish to start, and than call the startActivity method from your current context. 第二步是启动一个非常简单的活动,您需要使用当前上下文和要启动的活动的类创建一个intent,然后从当前上下文中调用startActivity方法。

In this case, the current context is represented by the activity reference. 在这种情况下,当前上下文由活动引用表示。

after this line 在这一行之后

ImageButton imageButton = holder.imageButton; 

just add this lines of code 只需添加此行代码

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

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

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