Java获取当前视图的引用_关于Java:如何在Android编程中获取当前的内容视图?

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

理想情况下,它将如下所示:

setContentView(R.layout.main); // sets the content view to main.xml

int contentView = getContentView(); // does this function exist?

我该怎么做?

AFAIK,无法获取内容视图。 你为什么需要它?

引用Android中有一种简单,通用的方法来获取布局的根视图吗?

This answer and comments give one method: [Get root view from current activity

findViewById(android.R.id.content)

Given any view in your hierarchy you can also call:

view.getRootView()

to obtain the root view of that hierarchy.

The"decor view" can also be obtained via getWindow().getDecorView(). This is the root of the view hierarchy and the point where it attaches to the window, but I'm not sure you want to be messing with it directly.

您只能通过id来对当前视图进行设置和获取

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);

}

希望这可以帮助。

这是行不通的。 super.onCreate()必须是该方法中要执行的第一行。stackoverflow.com/questions/8514405/oncreate-not-called

如果在任何行调用super.onCreate()都没有问题。 顺便说一句,我会为您移动该声明。

在活动中,您可以执行

View rootView = null;

View currentFocus = getWindow().getCurrentFocus();

if (currentFocus != null)

rootView = currentFocus.getRootView();

如上所述,还有

View decorView = getWindow().getDecorView();

以及

View decorView = getWindow().peekDecorView();

后两者的区别在于,如果尚未创建装饰视图,则peekDecorView()可能返回null,而如果还不存在,则getDecorView()将创建一个新的装饰视图。如果当前没有任何视图具有焦点,则第一个示例也可能返回null。

我还没有尝试过根视图和装饰视图是否是同一实例。但是,基于文档,我认为它们是正确的,并且可以用几行代码轻松地进行验证。

如果您有两个内容视图,则可以在每个视图的相对布局中放置一个标签。然后按标签名称获取视图。如果标签名称是唯一的愿望,那就怪了。希望对寻求解决方案的人有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值