java中的变量赋值语法

时间:2014-06-05 11:40:18

标签: java android

我正在尝试同时学习Android开发和java。

在此代码中:

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);
    Button b =  (Button)findViewById(R.id.button1);
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    Intent intent = new Intent(ActivityA.this, ActivityB.class);
    startActivity(intent);
        }
     });
    }

有人可以解释Button b = ... line - 是b的别名,为什么是findViewById之前的(Button)?

7 个答案:

答案 0 :(得分:2)

您必须将此View转换为Button小部件,它来自您的身份activity_layout的{​​{1}}。

button1

答案 1 :(得分:2)

Button b =  (Button)findViewById(R.id.button1);

findViewById()方法返回一个View,它是Button的超类。要将视图用​​作按钮,我们需要对其进行类型转换。这是因为Button(子类)的某些方法可能在View(超类)中不可用。

答案 2 :(得分:1)

它被称为TypeCasting

这里findViewById(R.id.btn_second)返回一个Button类型的视图,所以我们将它转​​换为Button类型。

Button b = (Button) findViewById(R.id.btn_second);

没有(Button)

findViewById(R.id.btn_second) will return a View.

Android UI对象都来自名为View的类型(文档here)。

答案 3 :(得分:1)

b是Button类型的变量。

(Button)表示将findViewById(...)的返回值强制转换为Button。

答案 4 :(得分:1)

查看findViewById方法的定义:http://developer.android.com/reference/android/app/Activity.html#findViewById(int) 它返回View类型,而不是Button。 但是View类有很多子类:http://developer.android.com/reference/android/view/View.html

Button,EditText,TextView等...... 因此,(Button)表示您将常规View类型转换为必需的,在XML布局中定义。

答案 5 :(得分:1)

当在赋值前写入变量类型时,它被称为TypeCasting:

所以在这种情况下:

float floatVariable = 10.2;
int test = (int) floatVariable;

将float转换为int。这是必要的,因为除非显式转换,否则int变量不能采用浮点数。

在你的情况下:

(Button)findViewById(R.id.button1)

方法findViewById()返回一个值,然后将其强制转换为Button。这是必要的,因为该方法不返回Button。

答案 6 :(得分:1)

方法findViewById返回一个视图。使用此代码,您将尝试找到一个给定其ID的按钮:

Button b = (Button) findViewById(R.id.button1);

您需要执行强制转换以将结果分配给Button变量。如果你没有将结果转换为Button,你将无法在b类中调用任何方法。