gpt4 book ai didi

java - 在静态方法中访问 getActivity()

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:52:31 26 4
gpt4 key购买 nike

我这里有这个调用方法setPoint的类

public class PointsList extends Fragment {    
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.listpoints, container, false);

public static class PointCreation extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.point_creation, container, false);
setPoint(view, CREATE);
return view;
}
}

static final void setPoint(View view, int goal) {
final EditText SerialField = (EditText) view.findViewById(R.id.Serial);
if(goal == CREATE) {
Button buttonGuardar = (Button) view.findViewById(R.id.buttonGuardar);
buttonGuardar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String Serial = SerialField.getText().toString();
pointsList.add(new Serial);
//go back to R.layout.listpoints
}
});
}
}

我的目标是在单击按钮将新序列号添加到列表后,我可以从

返回到上一个菜单
R.layout.point_creation to R.layout.listpoints

为了移动 fragment ,我通常使用这样的东西:

            Fragment fragment = new PointsList();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();

但里面:

static final void setPoint(View view, int goal)
getActivity().getSupportFragmentManager();

不能从静态上下文中引用,我不知道如何通过使静态类成为非静态来解决这个问题?我有一些我在静态类中使用的全局标志(有 2 个),因为

public class PointCreation(int something) extends Fragment 

我做不到。

最佳答案

您可以从 View 中获取 Activity :

Activity activity = (Activity)view.getContext()

如果您使用 FragmentActivity(似乎是这样),则将 Context 转换为 FragmentActivity(而不是常规 Activity),然后您将能够调用 getSupportFragmentManager()

FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();

关于java - 在静态方法中访问 getActivity(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990158/

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