popBackStackImmediate()返回空白屏幕

时间:2018-05-19 12:44:47

标签: java android fragment

我正在创建一个锻炼列表,使用RecycleViewer显示并使用RecycleViewer Adapter和ViewHolder填充。 RecycleViewer包含在片段中。

目标是显示一个新片段,显示所选(点击)锻炼的练习列表。

我设法用新片段替换片段以显示练习列表,但是当我按下后退按钮时,会显示一个空白屏幕。我不确定是什么导致了这种行为。理想情况下,当按下后退按钮时,将再次显示WorkoutsListFragment。

您能帮我理解并解决这个问题吗?

在我的WorkoutsActivity中我有这个:

public class WorkoutsActivity extends AppCompatActivity implements WorkoutsListFragment.onWorkoutSelectedInterface {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_workouts);

    WorkoutsListFragment workoutsListFragment = new WorkoutsListFragment();
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager
            .beginTransaction()
            .add(R.id.workouts_fragment_container, workoutsListFragment)
            .commit();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    getSupportFragmentManager().popBackStackImmediate();
}

@Override
public void onWorkoutSelected(int workoutId) {
    Log.i("****","workout : " + workoutId);
    ViewWorkoutFragment viewWorkoutFragment = new ViewWorkoutFragment();
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.workouts_fragment_container, viewWorkoutFragment)
            .addToBackStack(null)
            .commit();
}
}

为了保持简短,在WorkoutsListFragment中,我创建了onWorkoutSelectedInterface并在onAttach函数中赋值,在那里我得到了父活动。

然后我在onCreateView函数中设置了我的RecycleViewer。我将onWorkoutSelectedInterface传递给适配器,从中将相同的接口传递给ViewHolder。

My View持有人看起来像这样:

 WorkoutListViewHolder(View card, WorkoutsListFragment.onWorkoutSelectedInterface onWorkoutSelectedInterface) {
    super(card);
    this.title = card.findViewById(R.id.workout_card_title);
    this.subTitle = card.findViewById(R.id.workout_card_sub_title);
    this.icon = card.findViewById(R.id.icon);
    this.workoutId = 0;

    card.setOnClickListener((View v) -> {
        Log.i("view", ""+ this.workoutId);
        onWorkoutSelectedInterface.onWorkoutSelected(9);
    });
}

可在GitHub上找到完整代码: https://github.com/michalorestes/getFitApp/tree/master/app/src/main/java/com/jds/fitnessjunkiess/getfitapp/Activities/WorkoutsActivity

提前感谢您参与此活动:)

更新

我想我越来越接近理解这个问题了。 听起来很奇怪,this.dataSet.clear()删除属性中的所有数据(如预期的那样)和参数(意外!)。因此,在运行this.dataSet = dataSet时;视图未显示,因为没有要显示的数据。看起来两个变量都指向相同的内存位置:/

 public void swapData(List<Workout> dataSet){
    if (this.dataSet != null) {
        this.dataSet.clear();
        this.dataSet.addAll(dataSet);
    }
    else {
        this.dataSet = dataSet;
    }

    notifyDataSetChanged();
}

1 个答案:

答案 0 :(得分:1)

我通过将交换功能更改为:

解决了这个问题
    public void swapData(List<Workout> data){
    this.dataSet = data;
    notifyDataSetChanged();
}