如何在多个活动中使用相同的片段?

时间:2014-06-03 12:48:55

标签: android fragment

我正在使用片段,并希望在各种活动中分享它。但是,一旦我转向其他活动,它就会显示出来。这是活动:

public class ViewStubDemoActivity extends FragmentActivity
{
    public static ViewStub adStub;
    private AdFragment adFragment;
    public static FragmentManager fragmentManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        setHeader("ViewStub -> Header demo");

        if(fragmentManager == null)
            fragmentManager = getSupportFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        adFragment = (AdFragment)fragmentManager.findFragmentByTag("fragment");

        if(adFragment == null)
        {
            adFragment =  new AdFragment();

            fragmentTransaction.add (adFragment, "fragment");
            fragmentTransaction.replace(R.id.ad_fragment_linearLayout, adFragment);
            fragmentTransaction.commit();
        }
        else
        {
            fragmentTransaction.replace(R.id.ad_fragment_linearLayout, adFragment);
            fragmentTransaction.commit();
        }
    }

    public void setHeader(String title)
    {
        ViewStub stub = (ViewStub) findViewById(R.id.vsHeader);
        View inflated = stub.inflate();

        TextView txtTitle = (TextView) inflated.findViewById(R.id.txtHeading);
        txtTitle.setText(title);
    }

    public void changeActivity(View v)
    {
        Intent intent = new Intent(this, ViewStubDemoActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);

        intent = null;

        finish();

        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        return;
    }
}

这是片段:

public class AdFragment extends Fragment
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        this.setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {

        View view =  inflater.inflate(R.layout.ad_banner_layout, container, false);

        ViewGroup adBannerLinearLayout = (ViewGroup)view.findViewById(R.id.adBannerLayout);


        InMobiBanner inMobiBanner = new InMobiBanner(getActivity());
        inMobiBanner.loadInmobiBannerAd(adBannerLinearLayout);
        inMobiBanner = null;

        return view;
    }
}

请帮帮我。我尽了最大努力但没有用。

0 个答案:

没有答案