如何从android中的java类调用片段?

时间:2016-07-05 04:31:06

标签: android

我从java类调用一个片段,点击一个textview我调用一个片段这是我的onclick代码。

returnTheProduct.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
              FragmentManager fragmentManager = context.getFragmentManager();
              FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
              ProductReturnFragment productReturnFragment = new ProductReturnFragment();
              fragmentTransaction.replace(R.id.layout_marketplace_forms, new MarketPlaceFormsActivity());
              fragmentTransaction.addToBackStack(null);
              fragmentTransaction.commit();
            }
          });   

3 个答案:

答案 0 :(得分:0)

只需导入以下两个语句:

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

private FragmentTransaction mFragmentTransaction;
private FragmentManager mFragmentManager;
.....

然后在您的点击监听器上,您可以写下以下代码:

mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.layout_marketplace_forms, new ProductReturnFragment());
mFragmentTransaction.commit();

希望你得到答案。 :d

答案 1 :(得分:0)

添加如下:

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    if (isBackPressed)
        fragmentTransaction.addToBackStack(null);
    fragmentTransaction.replace(R.id.framelayout,attachedfragmentHere);
    fragmentTransaction.setCustomAnimations(R.anim.fade_in,R.anim.fade_out);
    fragmentTransaction.commit();

答案 2 :(得分:0)

From class call Activity on which you are calling fragments like below code.

Intent intent = new Intent(context, CallingActivity.class);

         intent.putExtra("key", "value");
          context.startActivity(returnFormIntent);

In your CallingActivity define below code.
private FragmentManager fragmentManager = getSupportFragmentManager(); 
private YourFragment yourFragment;

if (getIntent().hasExtra("key")) {
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      yourFragment = new YourFragment();
      fragmentTransaction.add(R.id.layout_your_fragment, yourFragment);
      fragmentTransaction.commit();

    }

like above we can call fragments from other nonActivity classes.