我想创建一个游戏,我需要创建一个类,我将发送ImageView的ID,并且该类创建一个具有此id的对象,以便我可以在ImageView上运行所有类函数。
示例:
假设我有3个带有id的M1,M2和M3的ImageView。 我想创建一个名为“myimg”的类,所以当我调用“myimg(M1)”时,该类创建一个对象,该对象将影响具有ID M1的“ImageView”并在M1上运行类“myimg”的所有函数。 / p>
public class myimg{
private ImageView m;
myimg(int id){
m = (ImageView) findViewById(R.id...)
}
}
答案 0 :(得分:0)
如果id值为R.id.XXXX,那么它将起作用:
myimg(int id){
m = (ImageView) findViewById(id);
}
Id id是一个String,它的值是R.id.XXXX中的XXXX然后它将起作用:
myimg(String res) {
int id = context.getResources().getIdentifier(res ,"id",getActivity().getPackageName());
m = (ImageView) findViewById(id);
}
答案 1 :(得分:0)
public class myimg{
ImageView m1,m2,m3 ;
ImageView chosenImageID ;
m1 = (ImageView) findViewById(R.id.imageView);
m2 = (ImageView) findViewById(R.id.imageView1);
m3 = (ImageView) findViewById(R.id.imageView2);
public ImageView myimg(ImageView id){
chosenImageID = id;
if(chosenImageID == m1)
return m1;
else if(chosenImageID == m2)
return m2;
else
return m3;
}
}
您可以使用myimg(ImageView)为您的其他方法确定所选的imageView。
答案 2 :(得分:0)
抓住这个。
public class MyImage {
private ImageView mImageView;
private Activity mActivity;
private ViewGroup mViewGroup;
public MyImage(Activity activity) {
mActivity = activity;
}
public MyImage(ViewGroup viewGroup) {
mViewGroup = viewGroup;
}
public MyImage(Activity activity,int id) {
mActivity = activity;
mImageView = createViewById(id);
}
public MyImage(ViewGroup viewGroup,int id) {
mViewGroup = viewGroup;
mImageView = createViewById(id);
}
public ImageView createViewById(int id) {
if (mActivity != null) {
ImageView view = mAcitivity.findViewById(id);
if (view == null)
throw new IllegalStateException("Can't find resource with id = " + id);
return view;
}
if (mViewGroup != null) {
ImageView view = mViewGroup.findViewById(id);
if (view == null)
throw new IllegalStateException("Can't find resource with id = " + id);
return view;
}
throw new IllegalStateException("Can't create view. Looks like a parent null.");
}
}
public void onCreate(...) {
MyImage image = new MyImage(this,R.id.my_image);
//Or
MyImage image = new MyImage(this);
image.createViewById(R.id.myImage);
}
注意:如果你将使用MyImage类,你应该确信ViewGroup(LinearLayout等)不是null。