我这里有一个类调用方法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 = 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
是我不能做的事。
答案 0 :(得分:19)
您可以从视图中获取活动:
Activity activity = (Activity)view.getContext()
如果您使用FragmentActivity(似乎是这样),那么将Context转换为FragmentActivity(而不是常规Activity),并且您将能够调用getSupportFragmentManager()
FragmentActivity activity = (FragmentActivity)view.getContext();
FragmentManager manager = activity.getSupportFragmentManager();
答案 1 :(得分:0)
您无法从静态对象引用到非静态对象。首先,我想到的是为你的片段使用单例模式。换句话说,添加片段单件片段:
static PointsList instance;
public PointsList getInstace(){
if(instance == null){
instance = new PointsList ();
}
return instance;
}
并在您的片段onCreate
方法中将其分配给实例:
instance = this;
之后,您可以从setPoint方法中删除 static 修饰符。并从项目的任何部分调用它,例如PointsList.getInstance().setPoint();
P.S。你必须使用静态的目标是什么?你应该非常小心地使用static
,许多事情可以通过单例而不是使用静态来完成。
答案 2 :(得分:0)
您可以通过以下代码使用;
private static FragmentActivity myContext;
@Override
public void onAttach(Activity activity) {
myContext = (FragmentActivity) activity;
super.onAttach(activity);
}
您可以将myContext
用作Context