两个片段之间的通信(android)

时间:2015-05-03 19:34:17

标签: android android-fragments

我的应用程序的屏幕分为两个片段(上部和下部)。上部片段是一个问题(QuizFragmentType1),下部片段(QuizFragment)包含一个“下一个”按钮,它正在改变上部片段。

如何通过按下片段中的“next”按钮从上层片段获取数据?

问题出在方法checkAnswers()中。当我尝试从QuizFragmentType1获取一些数据时,我做不到。例如:

RadioGroup grp = (RadioGroup) getView().findViewById(R.id.radioGroup1);

radioGroup1位于QuizFragmentType1的布局中,因此我无法达到它。 我显然错过了这两个片段之间的沟通。

有什么建议吗?

这是代码:

降低碎片(QuizFragment.java)

public class QuizFragment extends BaseFragment implements View.OnClickListener {

List<Question> quesList;
Button butNext;
EditText input_answer;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
int score = 0;
int qid = 0;
private GameActivity activity;
int i = 0;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment_quiz, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
    butNext = (Button) view.findViewById(R.id.button1);
    butNext.setOnClickListener(this);
    Random r = new Random();
    int Low = 1;
    int High = 3;
    int numb = r.nextInt(High - Low) + Low;

    if (numb == 1) {
        ((GameActivity) getActivity()).addFragment(R.id.game,
                new QuizFragmentType1());
    } else if (numb == 2) {
        ((GameActivity) getActivity()).addFragment(R.id.game,
                new QuizFragmentType2());
    }
}

public void randomQuestionType() {
    if (i < 5) {
        Random r = new Random();
        int Low = 1;
        int High = 3;
        int numb = r.nextInt(High - Low) + Low;

        if (numb == 1) {
            ((GameActivity) getActivity()).addFragment(R.id.game,
                    new QuizFragmentType1());
        } else if (numb == 2) {
            ((GameActivity) getActivity()).addFragment(R.id.game,
                    new QuizFragmentType2());
        }
        i++;
    }
    else {
        ((GameActivity) getActivity()).setupFragment(R.id.game,
                new ResultFragment());
    }

}

public void checkAnswers() {
    RadioGroup grp = (RadioGroup) getView().findViewById(R.id.radioGroup1);
    RadioButton answer = (RadioButton) getView().findViewById(
            grp.getCheckedRadioButtonId());

    String input = ((EditText) getView().findViewById(R.id.userInput))
            .getText().toString();

    if (currentQ.getAnswer().equals(answer.getText())) {
        score++;
        Log.d("score", "Your score" + score);

    } else if (currentQ.getAnswer().equals(input)) {
        score++;
        Log.d("score", "Your score" + score);
        input_answer.getText().clear();
    }
}

public void onClick(View v) {
    randomQuestionType();
}

}

Upper Fragment(QuizFragmentType1.java)或(QuizFragmentType2.java)

public class QuizFragmentType1 extends BaseFragment implements SetQuestionView {

static List<Question> quesList;
int qid = 0;
static Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;

float help = 0;
private GameActivity activity;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if (this.activity == null)
        this.activity = (GameActivity) activity;
    quesList = Question.getQuestions(this.activity.getCurrentCategory());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment_quiz_type1, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);

    Random br = new Random();
    currentQ = quesList.get(br.nextInt(quesList.size()));

    txtQuestion = (TextView) view.findViewById(R.id.textView1);
    rda = (RadioButton) view.findViewById(R.id.radio0);
    rdb = (RadioButton) view.findViewById(R.id.radio1);
    rdc = (RadioButton) view.findViewById(R.id.radio2);

    setQuestionView();

    for (int i = 0; i < quesList.size(); i++) {
        Log.d("Debug", "Pitanje " + i + ": "
                + quesList.get(i).getQuestion());
    }
}
public void setQuestionView() {
    txtQuestion.setText(currentQ.getQuestion());
    rda.setText(currentQ.getOptA());
    rdb.setText(currentQ.getOptB());
    rdc.setText(currentQ.getOptC());
    qid++;
}

}

1 个答案:

答案 0 :(得分:1)

您可以做的唯一方法是创建一个LocalBroadcastManager,一个可以处理所有应用程序组件的通信(交互)的类,即活动,片段,服务等。一旦您{ {1}}已注册Fragment,它可以与您的自定义LocalBroadcastManager进行通信。您不需要在清单中注册它,只需在您需要从其他组件接收信息的类中注册它。

在发件人类中,请致电:

IntentFilter

从接收器中,在Intent intent = new Intent("custom-event-name"); intent.putExtra("key", dataToBePassed);// may boolean, String, int, etc. LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 方法中注册:

onCreate()

此外,请确保您需要在LocalBroadcastManager.getInstance(context).registerReceiver(mMessageReceiver, new IntentFilter("custom-event-name")); 方法中取消注册:

onDestroy()

从接收器片段类中获取信息:

LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);

注意:如果您在private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("key"); Log.d("receiver", "Got message: " + message); } }; 上注册,请context更改getActivity()。如果在Fragment上,请更改为Activity

有关更多示例,请参阅this post