关于Android中findViewById(int id)方法的说明

Blu*_*tar 1 java android android-activity

我正在进行Head First Android开发,我对这个方法有点困惑 - > findViewById(int id)

我在文件"activity_find_beer.xml"中有以下按钮:

<Button
android:id="@+id/find_beer"
android:text="@string/find_beer"
android:onClick="onClickFindBeer" />
Run Code Online (Sandbox Code Playgroud)

以及来自FindBeerActivity.java类的以下代码,它将用户选择啤酒并在textview中显示相同的内容.

public class FindBeerActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_find_beer);
    }
    //Call when the button gets clicked
    public void onClickFindBeer(View view) {
        //Get a reference to the TextView
    TextView brands = (TextView) findViewById(R.id.brands);
       //Get a reference to the Spinner
    Spinner color = (Spinner) findViewById(R.id.color);
       //Get the selected item in the Spinner
    String beerType = String.valueOf(color.getSelectedItem());
       //Display the selected item
    brands.setText(beerType);
    }
    }
Run Code Online (Sandbox Code Playgroud)
  1. 我的问题是方法onClickFindBeer(View视图)将View类型的对象作为参数,但在我刚刚提到的xml中 android:onClick="onClickFindBeer",当用户单击该按钮时,onClickFindBeer方法被调用...谁传递的对象是类型查看到onClickFindBeer(视图)...是隐含的东西吗?

  2. 其次,在developer.android.com上,我看到方法 findViewById(int id)都在Activity类( https://developer.android.com/reference/android/app/Activity.html )中,也在视图中class https://developer.android.com/reference/android/view/View.html ...当我从中调用findViewById()时,我不清楚调用哪个类(Activity或View)findViewById(int id)方法onClickFindBeer(View view){}.

如果有人能够对此有所了解,那将是非常有必要的.

问候.

小智 5

  1. 该方法采用一个View参数,因为它是在类的超类中实现的Button(它是public class Button extends TextView.).您添加到XML的视图实际上是java类.将属性设置为此类XML项时,会相应地从特定的Java类构造对象.该课程的onClick方法View如下onClick(View v).通过设置XML,您只需要让Button类查找输入的方法,但其签名始终以View作为参数,该参数指向单击的视图.
  2. findViewById必须在View组上调用.但Actyvity类实现它以搜索由该setContentView()方法分配给它的视图中的项目.