我正在尝试以MainActivity
方式在我的布局中以编程方式添加片段,以便在其onCreate
方法中更具体。我一直收到错误Cannot resolve method add()
,这真的不应该发生,因为我从官方网站复制了代码。有人请帮忙。这是代码:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FooterVertical fragment = new FooterVertical();
fragmentTransaction.add(R.id.activity_main, fragment);
fragmentTransaction.commit();
public class FooterVertical extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FooterVertical() {
// Required empty public constructor
}
public static FooterVertical newInstance(String param1, String param2) {
FooterVertical fragment = new FooterVertical();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_footer_vertical, container, false);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
答案 0 :(得分:2)
如果您要导入android.app.Fragment;
,请将其更改为android.support.v4.app.Fragment;
答案 1 :(得分:0)
我用这个:
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();