将代码布局与xml布局文件链接

时间:2014-02-06 07:43:59

标签: android xml layout

我使用以下代码在背景上创建了一个包含9个灰色块的活动:

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(5);

    canvas.drawLine(width/3, 0, width/3, height, paint);
    canvas.drawLine((2*width)/3, 0, (2*width)/3, height, paint);
    canvas.drawLine(0, height/3, width, height/3, paint);
    canvas.drawLine(0, (2*height/3), width  , (2*height)/3, paint);

    Log.d("game","in draw");

    ImageView imageView = new ImageView(this);
    imageView.setImageBitmap(bitmap);

     layout = new RelativeLayout(this);

    RelativeLayout.LayoutParams params = new     RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT);
    layout.setId(1);
    params.addRule(RelativeLayout.CENTER_IN_PARENT);
    layout.addView(imageView, params);
    layout.setBackgroundColor(Color.BLACK);
    Log.d("game","before content view");

    // Show this layout in our activity.
    setContentView(layout);

所以我完全通过代码创建了一个布局。 现在我想将此布局与xml文件链接,以便在该活动中也可以看到该文件或代码中的任何更改。怎么做。

1 个答案:

答案 0 :(得分:0)

如果类从Activity,ListActivity,...等扩展,则可以。

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      }
}

您可以更改或添加代码布局:

setContentView(R.layout.activity_main); //activity_main is Layout you can change it