2016-09-28 73 views
-1

我試圖在MainActivity中編程添加一個片段到我的佈局中,在其onCreate方法中更具體。我一直收到一個錯誤Cannot resolve method add(),這真的不應該發生,因爲我從官方網站複製了代碼。有人請幫忙。下面是代碼:Android以編程方式添加片段不接受參數

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

您是否嘗試過清理的項目? –

+0

是的,多次但它沒有幫助 – zomlaaa95

+0

你也可以顯示FooterVertical片段和xml佈局文件代碼嗎? –

回答

2

如果要導入到android.support.v4.app.Fragment;

0

android.app.Fragment;改變它,我用這個:

FragmentManager fm = getFragmentManager(); 
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit(); 
相關問題