有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓理解Java语句“Button myButton=(Button)findViewById(R.id.my_Button);”

有人能解释一下这句话的语法吗

Button myButton = (Button) findViewById(R.id.my_button);

我认为这是在说“创建一个名为myButton的Button的新实例。”等号似乎表示myButton应该初始化为某个对象,但我的研究似乎表明等号后面的部分基本上是说myButton的这个实例连接到XML布局文件中定义的按钮

??“按钮”的意义是什么?它似乎有点多余

??myButton是否正在初始化,或者只是挂接到实际的XML按钮

??我正在搜索,找不到类似这样的Java语句的任何描述-这是Android Java独有的吗?有人能解释一下这里的语法吗

Thx


共 (4) 个答案

  1. # 1 楼答案

    (Button)它将findViewById(R.id.my_button);方法强制转换为按钮myButton对象

    public View findViewById (int id)

    Finds a view that was identified by the id attribute from the XML 
    that was processed in onCreate(Bundle)
    

    返回

    The view if found or null otherwise. 
    
  2. # 2 楼答案

    1.)myButtonButton类型的变量。这个绑定是通过声明Button myButton实现的

    2.)=运算符表示赋值。您正在将内容分配给变量myButton

    作业的内容是什么

    3.)一个android小部件,使用方法findViewById()#findViewById()返回,然后通过说(Button)将其转换为Button

    总之,,你有一个Button被分配给myButton,是的,这个按钮现在连接到xml按钮,带有你传递给findViewById()的id

  3. # 3 楼答案

    好吧,让我们先了解一下,安卓系统中的按钮是什么

    这是我们使用的XML语法:

    <Button android:id="@+id/my_button"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:text="CLICK ME!!" />
    

    现在在{}中,我们使用

     Button myButton = (Button) findViewById(R.id.my_button); //here we are invoking button ID from xml.
    

    对于actionListener,我们在这里使用:

    myButton.setOnClickEvent(new OnClickEvent(
              public void onClickEvent(View v){
                //DO SOMETHING AWESOME!
              }
            ));
    

    有关按钮的实际工作方式的更多信息,请单击here

  4. # 4 楼答案

    按钮是一个视图。findViewById(int id)将返回给定视图id的视图。由于findViewById只返回一个视图,因此需要将其强制转换为按钮,以便访问特定于按钮的方法