2017-08-29 57 views
0

開始片段嘗試使用此代碼如何從適配器類

public void startFragment(Context context, int position) { 
    Activity activity = (Activity) context; 
    android.app.FragmentManager manager = activity.getFragmentManager(); 
    android.app.FragmentTransaction fragmentTransaction = manager.beginTransaction(); 
    DepartmentDetails departmentDetails = new DepartmentDetails(); 

    Bundle bundle = new Bundle(); 
    bundle.putString("id", departmentList.get(position).id); 
    bundle.putSerializable("details", departmentList); 
    departmentDetails.setArguments(bundle); 

    fragmentTransaction.add(R.id.container, departmentDetails); 
    fragmentTransaction.commit(); 
} 

開始從適配器類片段,但它fragmentTransaction.add(R.id.container, departmentDetails);

強調紅色和在執行它表明

Error:(90, 28) error: no suitable method found for add(int,DepartmentDetails) 
method FragmentTransaction.add(Fragment,String) is not applicable 
(argument mismatch; int cannot be converted to Fragment) 
method FragmentTransaction.add(int,Fragment) is not applicable 
(argument mismatch; DepartmentDetails cannot be converted to Fragment) 
Error:Execution failed for task ':app:compileDebugJavaWithJavac'. 
> Compilation failed; see the compiler error output for details. 

這裏是我正在使用的DepartmentDetails片段代碼

public class DepartmentDetails extends Fragment implements CallBacks{ 

    ImageView ivProfile; 
    TextView tvName, tvBasicInfo, tvDescription; 
    String id, dean; 
    Departments details; 
    ArrayList<String> faculty, programs; 

    RequestParams params; 
    MyHttp myHttp; 
    String url; 

    public DepartmentDetails() { 
     // Required empty public constructor 
    } 
+1

什麼是DepartmentDetails片段或SupportFragment? –

+0

其簡單片段 – Asad

+1

請更新答案並添加DepartmentDetails片段 –

回答

1

您可以使用以下代碼從適配器類打開片段;

Fragment fragment = new MyFragment(); 
    FragmentManager fm = context.getSupportFragmentManager(); 
    FragmentTransaction ft = fm.beginTransaction(); 
    ft.replace(R.id.content_frame, fragment); 
    ft.commit(); 
1

添加在您的DepartmentDetails片段類

import android.support.v4.app.Fragment ; 

,而不是

import android.app.Fragment 
0

請下面的代碼試試。

Fragment fragment = new MyFragment(); 
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
    FragmentTransaction ft = fm.beginTransaction(); 
    ft.replace(R.id.content_frame, fragment); 
    ft.commit(); 
+0

getSupportFragmentManager在此處不顯示 – Asad

+0

檢查我更新的答案 –

+0

可能是現在如果'getSupportFragmentManager'沒有出現,則將其設置爲'context.getSUpportFragmentManager' –