安卓图片查看器
我有一个应用程序,目前只是一个图片库,下面有一个 ImageView,显示用户单击的图片。
目前我已经将这段代码拼凑在一起:
gallery.setOnItemClickListener(new OnItemClickListener() {
ImageView iv = (ImageView)findViewById(R.id.imageView1);
public void onItemClick(AdapterView parent, View v, int position, long id)
{
switch (position){
case 0 : iv.setImageResource(R.drawable.sample_1);break;
case 1 : iv.setImageResource(R.drawable.sample_2);break;
case 2 : iv.setImageResource(R.drawable.sample_3);break;
case 3 : iv.setImageResource(R.drawable.sample_4);break;
case 4 : iv.setImageResource(R.drawable.sample_5);break;
case 5 : iv.setImageResource(R.drawable.sample_6);break;
}
}
});
但是,如果我有数千张照片,我不想有一个巨大的 switch 语句,而是“sample_”的东西
我怎样才能用更少的代码行更快地重写这个函数。
我想我需要访问每个可绘制对象的 id..这可能吗?
非常感谢
艾德
I have an app that at the moment is just a gallery of pictures, with an ImageView below which shows the picture that the user has clicked on.
At the moment I have hacked together this code:
gallery.setOnItemClickListener(new OnItemClickListener() {
ImageView iv = (ImageView)findViewById(R.id.imageView1);
public void onItemClick(AdapterView parent, View v, int position, long id)
{
switch (position){
case 0 : iv.setImageResource(R.drawable.sample_1);break;
case 1 : iv.setImageResource(R.drawable.sample_2);break;
case 2 : iv.setImageResource(R.drawable.sample_3);break;
case 3 : iv.setImageResource(R.drawable.sample_4);break;
case 4 : iv.setImageResource(R.drawable.sample_5);break;
case 5 : iv.setImageResource(R.drawable.sample_6);break;
}
}
});
However, if I had thousands of photos I wouldn't want to have a massive switch statement, rather something where "sample_"
How can I rewrite this function to be faster with less lines of code.
I think I need to access the id of each of my drawables..is that possible?
Many thanks
Ed
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建 int[] picIds 数组的更简单方法是:
An easier way to create your int[] picIds array is:
您可以按如下方式进行:
这样,这只是一个可绘制对象命名约定的问题:您将可绘制对象称为“drawablename_1”、“drawablename_2”等...并且
getIdentifier()
检索它们的R
为您提供。You can proceed as follows:
This way this is just a matter of drawable naming convention: you call your drawables "drawablename_1", "drawablename_2", etc... and
getIdentifier()
retrieves theirR
ids for you.我会将您将使用的图像移动到您的资产文件夹中。您可以从资产文件夹中加载文件,就好像它们只是一个普通的 ole 目录一样,包括图片。然后,当您需要显示图片时,您的 OnClickListener 将如下所示:
请注意,加载图片是一个 O(1) 操作。
I would move your images you will be using to your Assets folder. You can load files from your asset folder as if they were just a plain ole directory, including pictures. Then when you need to show a picture, your OnClickListener would look like this:
Note that loading the picture is an O(1) operation.
保留一个与库中视图的顺序相同的 ID 数组
然后在您的点击侦听器中执行如下操作:
Keep an array of the IDs that is in the same order as the views in the gallery
Then in your click listener do something like this: