我在一个项目中走得很远,遇到了一个不受欢迎的障碍,无法找到解决方案。我有一些sudo代码,我相信它会说明我想要做的但不是完整的代码。尝试将其传递给ImageHandler时,Main类中的ContextWrapper上的错误是NullPointerException。不幸的是,ImageViews和我怀疑所有的视图,在活动调用onCreate之前尝试解决它们的drawable。所以我不得不尝试将图像存储到Activity Constructor中,但后来我无法传递上下文。我已经考虑过AsyncTask或处理程序来等待活动的onCreate(),但我还是可以回到SurfaceView并创建我自己的设计。我会继续看,但如果有更多Android经验的人,那么我知道更好的设计或解决方案,帮助将是巨大的。此外,兼容的eclipse布局预览器也是首选。我也试图让每个imageview独立地拥有所需的可绘图层,即使它们很多都相同但性能很糟糕。不得不在Activity中添加构造函数,因为如果在onCreate中创建了imagehandler,当ImageView尝试在它的构造函数上调用它时它将为null。为什么活动组件在调用Activity.onCreate之前就已经准备就绪,这是我还不太了解的事情。
public class MainActivity extends Activity {
ImageHandler ih;
MainActivity(){
Log.d("Acitivity", "Constructed");
ih=new ImageHandler(this);
//ih=new ImageHandler(this.getApplicationContext());
//ih=new ImageHandler(this.getBaseContext());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Activity", "Created");
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public LayerDrawable getImage(int some_identifier){
return ih.getImage(some_identifier);
}
}
===================
public class ImageHandler {
LayerDrawable[] image;
ImageHandler(Context context){
Log.d("ImageView", "Constructed");
//manipulate resource images to create custom layerdrawables and store.
//originally attempted to create a layer.xml and although it worked
//in the emulator perfectly the behavior was quite different in live tests.
//although it made sense any change to layer.xml images was global for all who used it
//the strange behavior was that the emulator behaved as desired.
}
public LayerDrawable getImage(int identifier){
return image[identifier];
}
}
====================
public class SomeImageView extends ImageView{
public SomeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
int some_identifier=0;
this.setImageDrawable(((MainActivity)context).getImage(some_identifier));
}
}
再次感谢社区的帮助。