12

我知道我可以通过说 setContentView(int) 在 Android 应用程序中设置视图的内容。有没有可以用来了解当前内容视图的功能?我不知道这是否有意义,但我正在寻找的是一个名为 getContentView 的函数,它返回一个 int。

理想情况下,它看起来像这样:

setContentView(R.layout.main); // sets the content view to main.xml
int contentView = getContentView(); // does this function exist?

我该怎么做?

4

4 回答 4

9

引用Android 中任何简单、通用的方法来获取布局的根视图?

这个答案和评论提供了一种方法:[从当前活动中获取根视图

findViewById(android.R.id.content)

给定层次结构中的任何视图,您还可以调用:

view.getRootView()

获取该层次结构的根视图。

“装饰视图”也可以通过 getWindow().getDecorView() 获得。这是视图层次结构的根,也是它附加到窗口的点,但我不确定你想直接弄乱它。

于 2012-11-16T03:01:10.503 回答
4

您可以仅通过 id 制作当前视图的 setter 和 getter

private int currentViewId = -1;

    public void setCurrentViewById(int id)
    {
        setContentView(id);
        currentViewId = id;
    }

    public int getCurrentViewById()
    {
        return currentViewId;
    }

然后在

protected void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setCurrentViewById(R.layout.main_layout);

}

希望这可以帮助。

于 2012-11-16T03:18:59.453 回答
3

在一个活动中,你可以做

View rootView = null;
View currentFocus = getWindow().getCurrentFocus();
if (currentFocus != null)
    rootView = currentFocus.getRootView();

如上所述,还有

View decorView = getWindow().getDecorView();

View decorView = getWindow().peekDecorView();

The difference between the latter two is that peekDecorView() may return null if the decor view has not been created yet, whereas getDecorView() will create a new decor view if none exists (yet). The first example may also return null if no view currently has focus.

I haven't tried out whether the root view and the decor view are the same instance. Based on the documentation, though, I would assume they are, and it could be easily verified with a few lines of code.

于 2016-01-27T08:39:45.387 回答
1

如果您有两个内容视图,那么您可以在每个内容的相对布局中放置一个标签。然后通过标签名称获取视图。如果标签名称是一个愿望,那么 blablabla。希望这对正在寻找解决方案的人有所帮助。

于 2013-06-09T12:36:52.767 回答