所以我制作了一个应用程序,您可以在其中输入一个片段上的按钮信息,然后将信息发送回活动,并将该片段替换为另一个片段,该片段将显示从第一个片段中检索到的信息。但是,我收到一个错误:" com.example.cribbage2.CardKeyboardFrag无法强制转换为com.example.cribbage2.PCResultsFrag"而且我不知道为什么。
以下是活动的相关代码:
package com.example.cribbage2;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import java.util.Arrays;
public class PointCalculator extends FragmentActivity implements CardKeyboardFrag.InfoTransfer {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_point_calculator);
//set cardKeyboardFrag
CardKeyboardFrag cardFrag = new CardKeyboardFrag();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, cardFrag);
transaction.addToBackStack(null);
transaction.commit();
//tell fragment how many cards you are requesting
}
public void cardNumSet(int cardNumMin, int cardNumMax){
CardKeyboardFrag cardKeyboardFrag = (CardKeyboardFrag) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
cardKeyboardFrag.cardNumGet(cardNumMin, cardNumMax);
}
public void displayResults(int[] resultsIntArray){
//parse intArray into String
String[] resultsStringArray = new String[4];
int loop = 0;
for (int num: resultsIntArray){
resultsStringArray[loop] = Integer.toString(num);
loop++;
}
//transfer to new fragment
PCResultsFrag resultsFrag = new PCResultsFrag();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, resultsFrag);
transaction.addToBackStack(null);
transaction.commit();
//this is the line where the error occurs
PCResultsFrag pcResultsFrag = (PCResultsFrag) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
pcResultsFrag.getResultsArray(resultsStringArray);
}
答案 0 :(得分:0)
尝试按照以下方式进行交易:
transaction.replace(R.id.fragment_container, resultsFrag , "resultsFrag");
然后像这样得到片段的对象:
Fragment currentFragment = getSupportFragmentManager().findFragmentByTag("resultsFrag");
currentFragment.getResultsArray(resultsStringArray);
答案 1 :(得分:-1)
您在findFragmentById中引用的资源ID是针对片段容器视图而不是相关片段。
bagof/3
和
PCResultsFrag pcResultsFrag = (PCResultsFrag) getSupportFragmentManager().findFragmentById(**R.id.fragment_container**);