我有16个imageview,每个设置为onBtnClick作为列表器,在此方法中它检查imageview id是否对应于特定的id,我需要更改它以便它检查imageview内的图像资源,例如
public void onBtnClicked(View v)
{
if( v.getId() == R.id.img1 )
{
Intent guess = new Intent(this, com.Logo_Master.Guesslogo.class);
guess.putExtra("image","img1");
startActivity(guess);
}
}
需要像:
public void onBtnClicked(View v)
{
if( v.getId() == R.drawable.img1 )
{
Intent guess = new Intent(this, com.Logo_Master.Guesslogo.class);
guess.putExtra("image","img1");
startActivity(guess);
}
}
或类似的东西.....所以它检查imageview内的图像而不是imageview ......
谢谢。
/ 修改 /
Random random = new Random( System.currentTimeMillis() );
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < imageViews.length; i++) {
int v = imageViews[i];
int next = random.nextInt( 16 );
if ( !generated.contains( next ) ) {
generated.add( next );
ImageView iv = (ImageView) findViewById( v );
iv.setImageResource( images[next] );
Object tag = (Object) new Integer(getImageName(this, String.valueOf(images[next])));
iv.setTag(tag);
}
else {
i--;
}
}
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("id/" + imageName + "guess", null, context.getPackageName());
}
public static int getImageName(Context context, String imageName)
{
return context.getResources().getIdentifier("drawable/" + imageName + "guess", null, context.getPackageName());
}
答案 0 :(得分:1)
您可以使用标签来实现此目的:
创建ImageView时(使用代码或XML格式),请定义标记:
android:tag = "tag"
OR
Object tag = (Object) new Integer(R.drawable.img1);
imageView.setTag(tag);
然后在需要之前检索标签:
Object tag = imageView.getTag();
int drawableId = Integer.parseInt(tag.toString());
if( drawableId == R.drawable.img1 ) {
....
}
祝你好运!
答案 1 :(得分:1)
无法直接使用imageView执行此操作。但是,没有什么可以阻止你继承imageView并添加所需的功能。例如:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;
public class MyImageButton extends ImageButton {
private static final String ANDROID_NAME_SPACE = "http://schemas.android.com/apk/res/android";
private int mDrawableResId = -1;
public MyImageButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
mDrawableResId = attrs.getAttributeResourceValue(ANDROID_NAME_SPACE, "src", -1);
}
public MyImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDrawableResId = attrs.getAttributeResourceValue(ANDROID_NAME_SPACE, "src", -1);
}
@Override
public void setImageResource(int resId){
super.setImageResource(resId);
mDrawableResId = resId;
}
public int getDrawableResId(){
return mDrawableResId;
}
}
这可以直接从XML中捕获drawable。
(diclaimer:我从来没有尝试过这个,但是它应该完全按照你想要的那样做。上面的例子在模拟器中有效。如果有人对这种方法有任何意见,我很乐意听到它们。)