gpt4 book ai didi

android - 如何在 Android 中从 Activity 移动到 Fragment?

转载 作者:行者123 更新时间:2023-11-30 00:55:12 25 4
gpt4 key购买 nike

请您告诉我从 Activity 移动到 Fragment 的最佳方式,以提供帮助。到目前为止,这是我所拥有的,但似乎没有用。这就是我调用函数 (getCategory) 的方式

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

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

在 Activity 中我试图移动到一个 fragment

public Fragment getCallCategory(int position) {


return new CallLogsFragment();
}

最佳答案

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

在 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");
}
}

在你的 Activity 中:

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();
}
}

当你想访问 fragment 实例的公共(public)方法时,使用 FragmentManager#findFragmentByTag(String tag) 来找到你的 fragment 实例:

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

更详细的解释,建议阅读fragments官方文档:https://developer.android.com/guide/components/fragments.html

关于android - 如何在 Android 中从 Activity 移动到 Fragment?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com