android – findViewById如何工作?

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搜索子视图.

在上面的代码中,谁是父视图,其子项被搜索给定的id?

最佳答案 对于Activity,findViewById从活动的内容视图(使用setContentView设置)开始搜索,该活动是从布局资源中扩展的视图层次结构.

点赞