2016-03-17 125 views
1

我在線路錯誤顯示片段Onclik

FragmentManager FM = getFragmentManager();

出於傳遞活動

。任何解決方案時,我點擊¿所以我need¿。謝謝和對不起I'm小白

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> { 

private List<ItemObject> itemList; 
private Context context; 


public RecyclerViewAdapter(Context context, List<ItemObject> itemList) { 
    this.itemList = itemList; 
    this.context = context; 
} 

@Override 
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) { 

    View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_list, null); 
    RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView); 
    return rcv; 
} 

@Override 
public void onBindViewHolder(final RecyclerViewHolders holder, final int position) { 
    holder.cardText.setText(itemList.get(position).getName()); 
    holder.cardPhoto.setImageResource(itemList.get(position).getPhoto()); 

    holder.itemView.setOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 

      switch (position){ 
       case 0: 



        FragmentManager fm = getFragmentManager(); 

        FragmentTransaction ft = fm.beginTransaction(); 
        ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame"); 
        ft.addToBackStack(null); 
        ft.commit(); 
+0

什麼錯誤? – Rohit5k2

回答

3

替換此:??

FragmentManager fm = getFragmentManager(); 

對此:

FragmentManager fm = ((Activity)context).getFragmentManager(); 

然後你的代碼應該看起來像:

FragmentManager fm = ((Activity)context).getFragmentManager(); 
FragmentTransaction ft = fm.beginTransaction(); 
ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame"); 
ft.addToBackStack(null); 
ft.commit(); 

或者

FragmentTransaction ft = ((Activity)context).getSupportFragmentManager().beginTransaction(); 
ft.replace(R.id.frameLayout, new FragmentNewGame(), "newGame"); 
       ft.addToBackStack(null); 
+0

隨着快速谷歌似乎'getFragmentManager'是一個'活動'的方法... - 有沒有做過年齡的Android/Java,但他可能工作 – urban

+0

[this](http://developer.android.com/reference/ android/app/Activity.html#getFragmentManager())表示'getFragmentManager'屬於Activity和[this](http://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html )表明'RecyclerView.Adapter'不會繼承Activity ...所以你的解決方案似乎是正確的。然而,我還沒有在Android上編碼2 - 3年......我不確定... – urban

+0

啊,別擔心,我在幾個月前面臨同樣的問題,我解決了這個問題,讓我們來看看如果它適合他:D –