gpt4 book ai didi

android - 多个 fragment 实例

转载 作者:行者123 更新时间:2023-11-29 01:33:11 26 4
gpt4 key购买 nike

我创建了一个 fragment ,我想添加多个实例:

public class myFragment extends Fragment {
int id;
public static myFragment newInstance(int id) {
myFragment fragment = new myFragment();
int id = id;
return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView idText = (TextView)
rootView.findViewById(R.id.idText);
idText.setText(id);
return rootView;
}

在我的主类中,

private int currentID;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
currentId = 0;
FragmentManager manager = getFragmentManager();
FragmentTransaction fragmentTransaction =
manager.beginTransaction();
oneFragment = new myFragment();
oneFragment.newInstance(currentId);
currentId = 2;
fragmentTransaction
.replace(R.id.container, oneFragment)
.commit();
twoFragment = new myFragment();
twoFragment.newInstance(currentId);
currentId = 3;

问题是,oneFragment 出现了 id 2。我不完全确定为什么会这样。容器是一个垂直方向的 LinearLayoutFragment 也是线性的。我想对所有 ID 重复使用我为 myFragment 编写的代码。

最佳答案

您的 MyFragment 类需要像这样传输 id:

public class MyFragment extends Fragment {

private final static String ID_KEY = "id_key";
public int id;

public static MyFragment newInstance(int id) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(ID_KEY, id);
fragment.setArguments(args);
return fragment;
}

public MyFragment() {
// Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID_KEY);
}
}
}

我认为您不需要创建 fragment 然后对其调用 newInstance()。我认为您只需调用 newInstance() 即可。试试这个:

private int currentID;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
currentId = 0;
FragmentManager manager = getFragmentManager();
FragmentTransaction fragmentTransaction =
manager.beginTransaction();
MyFragment oneFragment = MyFragment.newInstance(currentId);
currentId = 2;
fragmentTransaction
.replace(R.id.container, oneFragment)
.commit();
MyFragment twoFragment = MyFragment.newInstance(currentId);
currentId = 3;

关于android - 多个 fragment 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30113597/

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