Fragment中的OncreateView没有使用singleInstance进行调用

时间:2014-11-19 11:28:52

标签: android android-layout android-fragments

我有两个活动A和B,它们扩展了一个Base类Main,这个Base类在它的布局中有一个Framelayout,我们在活动A和B各自的布局中都包含它们。

我正在检查Fragment中片段的实例创建,当我进入特定的活动时,我也在膨胀。

我的代码是:

public class BaseAcitvity extends Activity {

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

这是我的FirstActivity ::

public class FirstActivity extends BaseAcitvity {

    public FirstFragment firstFragment ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstactivitylayout);
        firstFragment = new FirstFragment();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.card_view_layout,firstFragment).commit();

        Button buttonclick = (Button)findViewById(R.id.clickfirstactivity);
        buttonclick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent =  new Intent(getApplicationContext(),SecondActivity.class);
                startActivity(intent);
            }
        });
    }

}

public class SecondActivity extends BaseAcitvity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondactivity);

        FirstFragment fragment  = FirstFragment.getInstance();

        if(fragment == null)
        {
            fragment = new FirstFragment();
        }
        else { 
        FragmentManager fragmentManager = getFragmentManager();
        if(fragment !=null)
        {
        fragmentManager.beginTransaction().replace(R.id.card_view_layout,fragment).commit(); 
        }
        }       

    }

}

片段是::

public class FirstFragment extends Fragment {

    private static FirstFragment currentInstance;

        FirstFragment () {
        currentInstance = this;
    }

    public static synchronized FirstFragment  getInstance() {
        if (currentInstance == null) 
            currentInstance = new FirstFragment();
        return currentInstance;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_one, container, false);

    }

}

现在我的问题是,如果我已经在FirstActivity中创建了片段实例并检查了Fragment中的singleInstance,那么在SecondActivity时,为什么片段的OncreatView()不调用实例给出的非空值。< / p>

请帮帮我..那就是有办法调用OncreateView()来膨胀fragmentLayout。

0 个答案:

没有答案