简体   繁体   English

片段隐藏在后退按钮后

[英]Fragment hiding after back button

I have added a fragment inside an activity, by using below code: 我在活动中添加了一个片段,使用下面的代码:

    FragmentManager fragmentManager=getFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    PreferenceFragment preferencefragment=new Preferencefragment();
    fragmentTransaction.add(R.id.maincontainer, preferencefragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

Layout File: 布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<DigitalClock
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/digitalClock"
    android:layout_gravity="center"
    android:textColor="@color/appcolor"
    android:layout_centerHorizontal="true"
    style="@android:style/TextAppearance.DeviceDefault.Large"
    android:textSize="45dp"/>
<TimePicker
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/timePickersms" />

<FrameLayout
    android:id="@+id/maincontainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

The activity has digital clock and timepicker and below that the fragment gets displayed, now when I click on back button first the fragment disappears and later the previous activity is displayed. 活动有数字时钟和时间戳,下面显示片段,现在当我点击后退按钮时,片段消失,之后显示上一个活动。 How can the previous activity be displayed at one shot? 如何一次显示以前的活动?

The next question I have is how can I refresh the fragment when a button is pressed on the screen? 我的下一个问题是如何在屏幕上按下按钮时刷新片段?

addToBackStack(null) adds the fragment to back stack which is automatically popped out when back is pressed. addToBackStack(null)将片段添加到后台堆栈,当按下后退时会自动弹出。

So you can fix this by two methods (whichever suits you): 所以你可以通过两种方法解决这个问题(适合你):

remove addToBackStack(null) 删除addToBackStack(null)

OR 要么

add the following code to your activity: 将以下代码添加到您的活动中:

@Override
public void onBackPressed(){
    finish();
}

EDIT: 编辑:

As far as refreshing of fragment is concerned, you have two options again: First one is simply replace the old fragment by the older one. 就片段的刷新而言,你有两个选择:第一个是简单地用旧片段替换旧片段。 Second one is you can maintain a object of your fragment and have setter/getter functions for updating the data inside fragment. 第二个是你可以维护片段的对象,并具有用于更新片段内数据的setter / getter函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM