android实例按钮的差异实例化

时间:2014-09-15 08:44:01

标签: android

我'在Android上我是新的,我想知道声明按钮的区别是什么:

@Override
    protected void onCreate(Bundle savedInstanceState) {
    button = ((Button) findViewById(R.id.button));
    button.setOnClickListener(this);
}

@Override
    protected void onCreate(Bundle savedInstanceState) {
    button = new Button(this);
    button.setId(..);
    button = ((Button) findViewById(R.id.button));
    button.setOnClickListener(this);
}

提前感谢。

4 个答案:

答案 0 :(得分:2)

如果您声明Button in xml,那么您应该使用setContentView(int)layout提供Activity,并像这样初始化Button

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.your_layout);//a button with id button should present in this layout
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}

如果您想以编程方式创建Button,那么您应该像这样进行初始化

@Override
protected void onCreate(Bundle savedInstanceState) {
button = new Button(this);
button.setId(1);//some random integer value
setContentView(view);//some view
button.setOnClickListener(this);
}

setContentView(View view) for 2nd case

答案 1 :(得分:1)

如果使用第一个声明,则必须从xml定义一个按钮。在第二个中,您将以编程方式创建按钮。您还可以在视图等中定义它的位置。

答案 2 :(得分:1)

区别在于

xml based layout is comparatively fast

xml based code at the end it converted in to java code by the compiler

and if you will use the second approach you have to do allot of things like setting the

width and height, position where it to be shown and by doing that

Your code will be messy

So it its better to use xml based layouts 

答案 3 :(得分:1)

不同之处在于您第二次在代码中声明按钮。然后你添加一个id,大概是一个新的。 如果要运行第一个代码,则必须在xml布局资源文件中声明按钮。这是最快的方法,因为它在android框架上进行了优化,从xml读取布局(它实际上是转换为java,但是以优化的方式)。 第二个代码不需要布局文件,尽管您没有将按钮添加到布局中,因此现在的按钮不可用,因为它不是“在屏幕上”。