简体   繁体   English

具有不同主持人的相同片段

[英]Identical fragments with different presenters

I have an activity with 3 tabs: A, B & C. For every tab, I've created a fragment (-f) and presenter (-p). 我有一个带有3个选项卡的活动:A,B和C。对于每个选项卡,我都创建了一个片段(-f)和演示者(-p)。 The problem is that all three fragments (Af, Bf, Cf) are the same, but presenters are not. 问题在于所有三个片段(Af,Bf,Cf)都相同,但演示者却不同。 So the question is how I can avoid code duplicity? 所以问题是如何避免代码重复? I've tried to create a BaseFragment and extend it from Af, Bf, Cf, but if I'm in Af and something happens Cf (like UI update), then I receive java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setVisibility(int)' on a null object reference , because Cf at this is destroyed (am I right?) I don't want to create 3 same fragments with the same layouts. 我尝试创建BaseFragment并将其从Af,Bf,Cf扩展,但是如果我在Af中并且发生了Cf(例如UI更新),那么我会收到java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setVisibility(int)' on a null object reference ,因为这处的Cf被破坏了(是吗?),我不想创建3个具有相同布局的相同片段。

I've done something similar and I've found using Views a lot simpler and less buggy. 我做过类似的事情,并且发现使用Views更加简单,而且没有太多错误。 The android fragment managers can exhibit unpredictable behavior at times when executing various transactions. 执行各种事务时,Android片段管理器有时会表现出不可预测的行为。 Here's a quick sample of how it can work: 以下是其工作方式的快速示例:

YourActivity extends Activity {
      View a,b,c;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          a = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
          b = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
          c = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
      }
}

The activity is the presenter / controller for android, so I would go ahead and have the logic here instead of defining a presenter class for now. 该活动是android的presenter /控制器,因此我将继续进行讨论,并在此处进行逻辑介绍,而不是现在定义presenter类。 On each tab press you could then control which view to show. 然后,在每个选项卡上按,您都可以控制要显示的视图。 I don't see the code in which your are performing fragment transition so I cannot comment for sure if your fragment was destroyed. 我看不到您正在执行片段转换的代码,因此我无法确定您的片段是否被破坏。

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

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