【问题标题】:When is the Activity root view inflated?Activity 根视图何时膨胀?
【发布时间】:2019-03-22 16:35:53
【问题描述】:

Activity 类中的 setContentView() 方法的文档表明视图已添加到活动窗口并已膨胀。但是调用setContentView()后,根视图的宽高都为零。

下面的例子:

活动类

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "myTag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View root = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        // Here I expect the root view to have been inflated and have a width and height
        Log.i(TAG, "Root view width:" + root.getWidth() + " height:" + root.getHeight());
    }
}

布局 XML

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_gravity="center_horizontal|center_vertical" />

</FrameLayout>

我的问题是我需要在启动活动时创建根视图的位图图像,但我不确定何时应该这样做以保证根视图已膨胀。

【问题讨论】:

标签: android android-view


【解决方案1】:

正如@Onik 正确评论的那样,他已经在这里回答了我的问题Why does calling getWidth() on a View in onResume() return 0?

我要补充一点,您还可以将addOnLayoutChangeListener 附加到您的视图中,然后在onLayoutChange() 中将其删除。这很丑陋,但似乎是唯一的方法;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2016-04-06
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多