使用后退按钮转到主视图
我有一个带有主视图和一组子视图(定义为 XML)的应用程序。 我加载主视图:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
当我切换到另一个视图时,我会这样做:
holaPlayerBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view)
{
setContentView(R.layout.primerareceta);
};
要返回到我正在尝试的主视图:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
setContentView(R.layout.main);
return true;
}
return super.onKeyDown(keyCode, event);
}
但是这样做,我得到的是重新绘制的主视图,但它包含的按钮不起作用更长。
你知道为什么会发生这种情况吗? 我怎样才能回到主视图,并且所有按钮都像上次一样起作用?
感谢您的帮助 佩德罗
I have an app with a main view and a set of sub-views, defined as XMLs.
I load the main view with:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
When I switch to another view I do:
holaPlayerBtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view)
{
setContentView(R.layout.primerareceta);
};
To go back to the main view I am trying:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK){
setContentView(R.layout.main);
return true;
}
return super.onKeyDown(keyCode, event);
}
But doing this, what I get is the main view repainted, but the buttons that it contains are not functioning any longer.
Do you know why is happening this?
How can I go back to the main view with all its button functioning as in the previous time?
Thanks for your help
Pedro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用 setContentView 时,您正在替换屏幕上的内容。这有效地删除了您之前拥有的所有侦听器和视图。为此,您可能需要将原始初始化代码放在一个函数内,您可以在 onCreate 内部以及按下后退按钮时调用该函数。
当您要求的内容听起来像标准应用程序流程时,这似乎确实需要做很多工作。拥有一个主要活动会更容易,而不是更改视图,您应该使用 startActivity 在活动之间进行更改。这也将为您提供您想要的后退按钮行为,而无需编写任何代码来处理它。
When you call setContentView you are replacing what is on the screen. This effectively removes all listeners and views you had in place before. To do it you might want to but your original initialization code inside of a function that your can call inside of onCreate as well as when the back button is pressed.
This does seem like a lot of work when what you are asking for sounds like the standard application flow. It would be easier to have a main activity and instead of changing views you should be changing between activities using startActivity. This will also give you the behavior you desire with the back button without you having to write any code to handle it.
我认为您不能多次调用 setContentView 。不管怎样,你绝对不应该这样做。
ViewSwitcher javadoc
第一个示例
第二个示例
I don't think you're allowed to call setContentView more than once. And either way you definitely shouldn't.
ViewSwitcher javadoc
first example
second example
不要像这样切换布局。我建议使用单独的活动,或者您可以使用
ViewSwitcher
。Don't switch layouts like that. I'd recommend using separate activities or you can use the
ViewSwitcher
.