问题描述
package com.example.dell.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showToast(View view)
{
Toast t= new Toast(this);
LayoutInflater inflater=getLayoutInflater();
View v=inflater.inflate(R.layout.toast, (ViewGroup) findViewById(R.id.toastViewGroup));
t.setView(v);
t.show();
}
}
来自android开发者网站findViewById
搜索具有给定ID的子视图.
From the android developer sitefindViewById
searches for child views with give id.
在上面的代码中,谁是父视图,正在为其给定的id搜索其子视图?
In the above code, who is the parent view, whose children are being searched for given id?
推荐答案
活动中的根视图由setContentView(int layoutId)
或setContentView(View rootView)
确定.
The root view in an Activity is determined by setContentView(int layoutId)
or setContentView(View rootView)
.
您的情况是
setContentView(R.layout.activity_main);
因此,您对findViewById
进行的任何调用都会从activity_main.xml
查找ID.
Therefore, any call you make to findViewById
will lookup the id from activity_main.xml
.
如果找不到您指定的ID,它将返回null.
If it is unable to find the id that you have specified, it will return null.
值得一提的是,您没有调用该方法,这通常是制作Toast的方法.
It is worth mentioning that that you aren't calling that method and this is typically how a Toast is made.
Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();
这篇关于findViewById如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!