返回对象或对象的引用

时间:2017-11-08 11:57:27

标签: android casting findviewbyid

findViewById()inflate()是否会返回视图对象或"查看参考" ?, 问因为我们做了

LinearLayout linear=(LinearLayout)inflate(R.layout.main,null);

因此,如果膨胀返回视图对象,并且视图是LinearLayout的父级,那么查看对象如何包含linearLayouts成员变量和方法。

2 个答案:

答案 0 :(得分:0)

// use this in activity
LinearLayout ll=(LinearLayout)findViewById(R.id.llout);

// use this in fragment onViewCreated()
LinearLayout ll=(LinearLayout)View.findViewById(R.id.llout);

// used anywhere in actvity or fragment
LinearLayout ll=(LinearLayout)getView.findViewById(R.id.llout);

答案 1 :(得分:0)

  

findViewById()和inflate()是否返回视图对象或"查看引用" ?

它返回一个View(或子类)对象。

  

如果膨胀返回视图对象,并且视图是LinearLayout的父级,则视图对象如何包含linearLayouts成员变量和方法。

当您为视图充气时,布局中的所有视图都会被夸大,但返回的对象将是布局中的顶级视图。许多观点(任何来自ViewGroup的观点)都可以拥有" child"观点。您可以致电findViewById()或直接通过getChildAt()访问返回视图的子项。

我们说我们有这种布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello world"/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Stack Overflow"/>

</LinearLayout>

我们可以编写这样的代码:

LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_layout, null);

在这种情况下,view将是LinearLayout,它是我们布局中的顶级视图。如果我们想要得到孩子TextView,我们可以这样写:

TextView helloWorld = view.findViewById(R.id.text1);
TextView stackOverflow = ((LinearLayout) view).getChildAt(1); // index is 0-based
相关问题