如何从Android中的活动转移到片段?

时间:2016-10-27 08:38:01

标签: android android-fragments android-activity

请您告诉我从活动转移到片段的最佳方式。这是我到目前为止,但似乎没有工作。 这就是我调用函数(getCategory)

的方式
private void selectItem( int group, int usage)
   {
      if (!shown) return;
      classificationGroup = group;

      ((DashboardActivity)getActivity()).getCallCategory(classificationGroup);
   }

在活动中我试图转移到片段

public Fragment getCallCategory(int position) {


      return new CallLogsFragment();
   }

1 个答案:

答案 0 :(得分:0)

创建片段的标准模式如下所示:

在fragment类中(确保导入android.support.v4.app.Fragment):

public class MyFragment extends Fragment {

    public static final String TAG = "MyFragment";

    private int position;

    // You can add other parameters here
    public static MyFragment newInstance(int position) {
        Bundle args = new Bundle();
        // Pass all the parameters to your bundle
        args.putInt("pos", position);
        MyFragment fragment = new MyFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.position = getArguments().getInt("pos");
    }
}

在您的活动中:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Add your parameters
        MyFragment fragment = MyFragment.newInstance(10);
        // R.id.container - the id of a view that will hold your fragment; usually a FrameLayout
        getSupportFragmentManager().beginTransaction()
            .add(R.id.container, fragment, MyFragment.TAG)
            .commit();
    }
}

如果要访问片段实例的公共方法,请使用FragmentManager#findFragmentByTag(String tag)查找片段实例:

    MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(MyFragment.TAG);
    if(fragment != null){
        // Do something with fragment
    }

有关更详细的说明,建议您阅读有关片段的官方文档:https://developer.android.com/guide/components/fragments.html