【问题标题】:Passing Boolean value from fragments to activity将布尔值从片段传递给活动
【发布时间】:2017-01-24 13:39:10
【问题描述】:

我是 android 开发的新手,我正在尝试将布尔值从对话框片段传递给活动。

布尔值应该由用户决定(取决于用户点击了哪个按钮)。但是,没有点击任何按钮,布尔值立即变为 false。

我尝试了各种我在网上找到的推荐方法,但没有一个适合我(我想我有些地方搞砸了......),这些方法包括:

-广播 - 实现接口 -intent.putExtra

下面是我想出的代码,有人可以帮我看看吗?任何帮助表示赞赏。

阶段:

package com.example.fuj.valorsafeworldbytrade;

import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;

public class Stage extends AppCompatActivity {

String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();

public void setText(){
    TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
    TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
    TextView pGoldText = (TextView) findViewById(R.id.player_gold);
    TextView pRepText = (TextView) findViewById(R.id.player_reputation);
    cpuReputation.setText(String.valueOf(basicInfo.cRep));
    cpuGold.setText(String.valueOf(basicInfo.cGold));
    pGoldText.setText(String.valueOf(basicInfo.pGold));
    pRepText.setText(String.valueOf(basicInfo.pRep));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stage);
    setText();

}

protected void onStart() {
    super.onStart();
    stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}


public void playerChoice(View view) {
    boolean deceiveEnabled;
    switch (view.getId()) {
        case R.id.cooperate_button:
            deceiveEnabled = false;
            break;

        case R.id.deceive_button:
            deceiveEnabled = true;
            break;

        default:
            throw new  RuntimeException("Unknown Button ID");
    }
    switch (stage){
        case "xumo":
            xuMo(deceiveEnabled);
            break;

    }


}

public void xuMo(boolean playerDeceiveEnabled){
    boolean cpuDeceiveEnabled;
    cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);

    if (cpuDeceiveEnabled){
        if (playerDeceiveEnabled){
            basicInfo.playerDvsCpuD();
            // faith changes to be amend w/ proper value, need record on the change of status
        }
        if (!playerDeceiveEnabled){
            basicInfo.playerCvsCpuD();
        }
    }

    if (!cpuDeceiveEnabled){
        if (playerDeceiveEnabled){
            basicInfo.playerDvsCpuC();
        }
        if (!playerDeceiveEnabled){
            basicInfo.playerCvsCpuC();
        }
    }
    if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
        //to be changed
        setText();
        losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
//trying to show a alert dialog fragment
        Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));

        if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
//This is the part that I wanted to retrieve data from the user(if they want to try again or not)
            basicInfo.reset();
            losingDialogFragment.dismiss();

        }else{
            losingDialogFragment.dismiss();
        }
    }
    setText();
        // to be changed

}
}

LosingDialogFragment:

package com.example.fuj.valorsafeworldbytrade;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
 * Created by fuj on 20/1/2017.
 */

public class LosingDialogFragment extends DialogFragment{

public static final String LOSING_FRAGMENT = "LOSING";
public boolean tryAgainEnabled;

Intent intent = new Intent();


@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;
//the following code is used to set the boolean value after the user click the button

    final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
    tryAgainButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tryAgainEnabled = true;
        }
    });

    Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
    giveUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tryAgainEnabled = false;
        }
    });
    getDialog().setTitle(LOSING_FRAGMENT);
    return rootView;
}
}

我也很抱歉我的英语不是最好的,如果因为我的英语不好有什么不清楚或不礼貌的地方,请告诉我。对于我所犯的任何错误,我提前道歉。

【问题讨论】:

  • 在主要活动中创建静态布尔值并在对话框片段中使用它
  • 你想达到什么,你能在代码中显示吗?
  • @Divyesh 静态不是最好的方法
  • @AJay 很抱歉我没有提供足够的信息

标签: android android-fragments


【解决方案1】:

这是因为您在显示Dialog 后正好检查了tryAgainEnabled 的值。 Dialog 开始于Asynchronously,这意味着它以不同的Thread 开始,并且您当前的线程不会等待关闭Dialog,因此您的代码if(losingDialogFragment.tryAgainEnabled){ 的这行代码恰好在您显示对话框之后运行,在您之前将值设置为tryAgainEnabled。因为boolean 的默认值始终是false,所以每次都会得到false

我建议为此使用监听器:

对话框:

public class LosingDialogFragment extends DialogFragment {

    public static final String LOSING_FRAGMENT = "LOSING";
    public boolean tryAgainEnabled;

    Intent intent = new Intent();


    private View.OnClickListener onTryAgainButtonClickLisnter;
    private View.OnClickListener onGiveUpButtonClickLisnter;
    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;

        final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
        tryAgainButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if(onTryAgainButtonClickLisnter!=null)
                onTryAgainButtonClickLisnter.onClick(v);
            }
        });

        Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
        giveUpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onGiveUpButtonClickLisnter!=null)
                    onGiveUpButtonClickLisnter.onClick(v);
            }
        });
        getDialog().setTitle(LOSING_FRAGMENT);
        return rootView;
    }

    public void setOnTryAgainButtonClickLisnter(View.OnClickListener onTryAgainButtonClickLisnter) {
        this.onTryAgainButtonClickLisnter = onTryAgainButtonClickLisnter;
    }

    public void setOnGiveUpButtonClickLisnter(View.OnClickListener onGiveUpButtonClickLisnter) {
        this.onGiveUpButtonClickLisnter = onGiveUpButtonClickLisnter;
    }
}

在您的活动调用对话框中,如下所示:

LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
    losingDialogFragment.setOnTryAgainButtonClickLisnter(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tryAgain();
            losingDialogFragment.dismiss();
        }
    });
    losingDialogFragment.setOnGiveUpButtonClickLisnter(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            giveUp();
            losingDialogFragment.dismiss();
        }
    });
losingDialogFragment.show(fragmentManager, "");

【讨论】:

  • 我试过你的方法,但似乎对我不起作用
  • 我担心我做错了......但我复制了错误声明,所以你可能想看看
  • 致命异常:主进程:com.example.fuj.valorsafetheworldbytrade,PID:3931 java.lang.IllegalStateException:无法为 android:onClick 执行方法
  • 哎呀...原来我搞砸了,现在运行正常!
【解决方案2】:

在您的Stage 活动中声明public boolean tryAgainEnabled;,然后您可以使用((Stage)context).tryAgainEnabled 更新该变量。

    package com.example.fuj.valorsafeworldbytrade;

import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import static com.example.fuj.valorsafeworldbytrade.LosingDialogFragment.LOSING_FRAGMENT;

public class Stage extends AppCompatActivity {

String stage;
FragmentManager fragmentManager = getSupportFragmentManager();
LosingDialogFragment losingDialogFragment = new LosingDialogFragment();
BasicInfo basicInfo = new BasicInfo();
public boolean tryAgainEnabled;
public void setText(){
    TextView cpuReputation = (TextView) findViewById(R.id.cpu_reputation);
    TextView cpuGold = (TextView) findViewById(R.id.cpu_gold);
    TextView pGoldText = (TextView) findViewById(R.id.player_gold);
    TextView pRepText = (TextView) findViewById(R.id.player_reputation);
    cpuReputation.setText(String.valueOf(basicInfo.cRep));
    cpuGold.setText(String.valueOf(basicInfo.cGold));
    pGoldText.setText(String.valueOf(basicInfo.pGold));
    pRepText.setText(String.valueOf(basicInfo.pRep));
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stage);
    setText();

}

protected void onStart() {
    super.onStart();
    stage = getIntent().getStringExtra(StageChoosingMenu.STAGE);
}


public void playerChoice(View view) {
    boolean deceiveEnabled;
    switch (view.getId()) {
        case R.id.cooperate_button:
            deceiveEnabled = false;
            break;

        case R.id.deceive_button:
            deceiveEnabled = true;
            break;

        default:
            throw new  RuntimeException("Unknown Button ID");
    }
    switch (stage){
        case "xumo":
            xuMo(deceiveEnabled);
            break;

    }


}

public void xuMo(boolean playerDeceiveEnabled){
    boolean cpuDeceiveEnabled;
    cpuDeceiveEnabled = (Math.random() - basicInfo.faith > 0);

    if (cpuDeceiveEnabled){
        if (playerDeceiveEnabled){
            basicInfo.playerDvsCpuD();
            // faith changes to be amend w/ proper value, need record on the change of status
        }
        if (!playerDeceiveEnabled){
            basicInfo.playerCvsCpuD();
        }
    }

    if (!cpuDeceiveEnabled){
        if (playerDeceiveEnabled){
            basicInfo.playerDvsCpuC();
        }
        if (!playerDeceiveEnabled){
            basicInfo.playerCvsCpuC();
        }
    }
    if(basicInfo.pGold <= 0 || basicInfo.cGold <= 0 || basicInfo.pRep <= 0 || basicInfo.cRep <= 0){
        //to be changed
        setText();
        losingDialogFragment.show(fragmentManager,LOSING_FRAGMENT);
        Log.d("True", String.valueOf(losingDialogFragment.tryAgainEnabled));

        if(losingDialogFragment.tryAgainEnabled){//tryAgainEnabled is always false
            basicInfo.reset();
            losingDialogFragment.dismiss();
        }else{
            losingDialogFragment.dismiss();
        }
    }
    setText();
        // to be changed

}
}

在片段中

package com.example.fuj.valorsafeworldbytrade;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
 * Created by fuj on 20/1/2017.
 */

public class LosingDialogFragment extends DialogFragment{

public static final String LOSING_FRAGMENT = "LOSING";
Context context;
Intent intent = new Intent();


@Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.fragment_lose, container, false);;

    final Button tryAgainButton = (Button)rootView.findViewById(R.id.try_again_button);
    tryAgainButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((Stage)context).tryAgainEnabled = true;
        }
    });

    Button giveUpButton =(Button)rootView.findViewById(R.id.give_up_button);
    giveUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((Stage)context).tryAgainEnabled = false;
        }
    });
    getDialog().setTitle(LOSING_FRAGMENT);
    return rootView;
}
}

【讨论】:

  • 对不起... tryAgainEnabled 的值仍然是 false
猜你喜欢
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多