简体   繁体   English

从OnClickListener替换片段

[英]Replace Fragment from OnClickListener

I'm running into trouble. 我遇到麻烦了。 I have a Fragment with an onclicklistener. 我有一个带有onclicklistener的片段。 The fragment calls "ClickMe" which is in my Activity that hosts the fragment. 该片段称为“ ClickMe”,该片段位于承载片段的我的活动中。 However, in order for ClickMe to not error out, ClickMe has to be static. 但是,为了使ClickMe不会出错,ClickMe必须是静态的。 But, Clickme can't be static because then getFragmentManager errors out. 但是,Clickme不能是静态的,因为这会导致getFragmentManager错误。 Essentially I'm trying to create a game. 本质上,我正在尝试创建一个游戏。 A click will put a new fragment over the top of the old one (as you have to do the same thing 10 times in a row in my game. Here's the code: 单击将在旧片段的顶部放置一个新片段(因为您必须在游戏中连续执行10次相同的操作。这是代码:

Fragment: 分段:

text1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(loc1 == 10 || loc2 ==10){
            //Text if user wins
            BlankFragment.counter ++;
            BlankFragment.ClickMe(BlankFragment.counter);

            Log.i("Win: ", "Yay");
        }else{
            //Text if user loses

            Log.i("Lose: ", "Boo");
        }
    }
});

MainActivity: 主要活动:

public void ClickMe(int count){
Fragment newFragment;
counter = count;
if(counter > 5){
    newFragment = new g3by3Fragment();
}else{
    newFragment = new g3by3Fragment();
}

FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();

Thank you for your help! 谢谢您的帮助!

You don't have to preform FragmentTransactions from the Activity . 您不必从Activity FragmentTransactions You can just add well preform them from the Fragment . 您可以从Fragment添加预成型的文件。 Your detour into the Activity through ClickMe is unnecessary. 您无需通过ClickMe绕道进入Activity I know you probably do this because the logic of your game is in the Activity but that is not optimal. 我知道您可能这样做是因为您的游戏逻辑在Activity但这并不是最佳选择。 Let the Fragments themselves decide which Fragment comes next or implement a Singleton which takes care of your game logic. Fragments本身决定下一个Fragment或者实现一个照顾游戏逻辑的单例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM