findViewById如何工作? [英] How does findViewById work?

查看:74
本文介绍了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的子视图.

From the android developer site findViewById 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如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆