按钮在我在片段中按返回键时不可见。

huangapple 未分类评论50阅读模式
英文:

Button is not visible when I back press in fragment

问题

我在主活动中有三个按钮。当我点击任何一个按钮时,会打开一个新的片段。在我点击后不久,这三个按钮就会消失。点击按钮会打开片段。当我从片段返回时,主活动中的所有三个按钮都不可见。我希望从片段返回到活动时,所有三个按钮都是可见的。

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. btn = findViewById(R.id.bn1);
  6. btn1 = findViewById(R.id.bn2);
  7. btn2 = findViewById(R.id.bn3);
  8. btn.setOnClickListener(new View.OnClickListener() {
  9. @Override
  10. public void onClick(View v) {
  11. btn.setVisibility(View.GONE);
  12. btn1.setVisibility(View.GONE);
  13. btn2.setVisibility(View.GONE);
  14. FragmentManager fm = getSupportFragmentManager();
  15. TestFragment fragment = new TestFragment();
  16. fm.beginTransaction().add(R.id.fragment_container, fragment).addToBackStack(null).commit();
  17. }
  18. });
  19. }

请注意,这只是代码的一部分,用于在点击按钮时隐藏按钮并打开片段。要实现从片段返回时重新显示按钮,您需要在片段的相应位置进行更多处理。

英文:

I have three buttons inside the main activity. When I click on any of the buttons, a new fragment opens. Visibility of the three buttons disappears as soon as I click. Clicking on the button opens the fragments. When I press back from fragment, all three buttons in the man activity are not visible. I want all three buttons to be visible when I come back to activity from fragments.

  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. btn = findViewById(R.id.bn1);
  6. btn1 = findViewById(R.id.bn2);
  7. btn2 = findViewById(R.id.bn3);
  8. btn.setOnClickListener(new View.OnClickListener() {
  9. @Override
  10. public void onClick(View v) {
  11. btn.setVisibility(GONE);
  12. btn1.setVisibility(GONE);
  13. btn2.setVisibility(GONE);
  14. FragmentManager fm = getSupportFragmentManager();
  15. TestFragment fragment = new TestFragment();
  16. fm.beginTransaction().add(R.id.fragment_container,fragment).addToBackStack(null).commit(); }});

答案1

得分: 0

在您的onClick中。一旦按钮被点击,您将按钮的可见性设置为消失。您是否希望这样做?如果是这样,那么在您的create中,将按钮的可见性设置为可见,例如btn.setVisibility(VISIBLE)。请在您执行findViewByID的位置正下方进行此操作。OnCreate每次启动活动时都会被调用,因此您应该在这里执行您希望活动在启动时具有的所有操作。希望这能帮助您。

英文:

In your onClick. Once a button is clicked you set the visibility of the buttons to gone. Is this something you want to do? If so, in your create, set the visibility of the buttons to visible e.g btn.setVisibility(VISIBLE). Do this right under where you do your findViewByID's. Oncreate is called every time you initiate your activity, therefore you should do everything here you want your activity to have when starting up. Hope this helps

huangapple
  • 本文由 发表于 2020年5月3日 19:46:12
  • 转载请务必保留本文链接:https://java.coder-hub.com/61573901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定