【发布时间】:2014-05-11 09:27:11
【问题描述】:
我正在进行一项实验,以在 MainActivity 中以编程方式创建布局。在MainActivity 中,还有一个SurfaceView 元素。我知道 LayoutInflater 可用于将 XML 膨胀为 View 对象,但无法弄清楚当一切都在代码中时它是如何完成的。
下面的代码给出了一个 RuntimeException 和 NullPointerException 错误
public class MainActivity extends Activity implements Runnable {
private SurfaceView p_view;
private boolean p_running;
private Thread p_thread;
private RelativeLayout p_rLayout;
private int p_picNum;
private Bitmap p_picImage;
private ImageView p_imgV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//RelativeLayout p_rLayout with an ImageView component
p_rLayout = new RelativeLayout (this);
p_rLayout.setLayoutParams(new RelativeLayout.LayoutParams (
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
p_imgV = new ImageView(this);
p_picNum = getResources().getIdentifier(
"square", "drawable", getPackageName());
p_picImage = BitmapFactory.decodeResource (getResources(), p_picNum);
p_imgV.setImageBitmap(p_picImage);
p_rLayout.addView(p_imgV, new RelativeLayout.LayoutParams (
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//A SurfaceView-element for drawing a circle
p_view = new SurfaceView(this);
//Inflate p_rLayout to the SurfaceView-element p_view
ViewGroup viewGroup = (ViewGroup)this.getLayoutInflater().inflate(
null, p_rLayout);
viewGroup.addView(p_view);
setContentView(viewGroup);
p_thread = new Thread(this);
p_thread.start();
p_running = true;
}
@Override
public void run() {
while(p_running) {
if(p_view.getHolder().getSurface().isValid()) {
p_canvas = p_view.getHolder().lockCanvas();
//Draw a circle
p_view.getHolder().unlockCanvasAndPost(p_canvas);
}
}
}
}
【问题讨论】:
-
同时发布 logcat stacktrace 以获得更多帮助
-
并为
p_imgVImageView 添加高度和宽度参数
标签: android xml surfaceview layout-inflater