【问题标题】:returns an object or a refrence to object返回一个对象或对对象的引用
【发布时间】:2017-11-08 11:57:26
【问题描述】:

findViewById()inflate() 是否返回视图对象或“视图引用”? 问是因为我们这样做了

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

所以如果inflate返回视图对象,并且视图是LinearLayout的父级,那么视图的对象怎么可能包含linearLayouts成员变量和方法。

【问题讨论】:

  • 看来您错过了 Java 基础知识。

标签: android casting findviewbyid


【解决方案1】:

findViewById() 和 inflate() 是否返回视图对象或“视图引用”?

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

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

当您膨胀视图时,布局中的所有视图都将膨胀,但返回的对象将是您布局中的顶级视图。许多视图(源自ViewGroup 的任何视图)都可以有“子”视图。您可以通过调用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,这是我们布局中的顶级视图。如果我们想得到孩子TextViews,我们可以这样写:

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

【讨论】:

    【解决方案2】:
    // 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);
    

    【讨论】:

    • 他们是返回一个“view obj”本身还是一个“对对象的类型视图的引用”
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-09-19
    • 2015-10-26
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多