如何在非活动java类中管理片段?

时间:2018-04-21 08:58:50

标签: java android android-fragments inheritance

我的项目中有2个不同的片段。我想从抽象类继承这些片段。但我无法为FragmentManager编写正确的代码来隐藏或显示片段。我怎样才能做到这一点?

Error : E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.bengisu.bitirme, PID: 2580
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bengisu.bitirme/com.example.bengisu.bitirme.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                      at android.os.Handler.dispatchMessage(Handler.java:110)
                      at android.os.Looper.loop(Looper.java:203)
                      at android.app.ActivityThread.main(ActivityThread.java:6251)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
                   Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class fragment
                   Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class fragment
                   Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.bengisu.bitirme.GameBoard: calling Fragment constructor caused an exception
                      at android.support.v4.app.Fragment.instantiate(Fragment.java:481)
                      at android.support.v4.app.FragmentContainer.instantiate(FragmentContainer.java:33)
                      at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3664)
                      at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
                      at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:338)
                      at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:39)
                      at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:861)
                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                      at com.example.bengisu.bitirme.MainActivity.onCreate(MainActivity.java:30)
                      at android.app.Activity.performCreate(Activity.java:6666)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2789)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                      at android.os.Handler.dispatchMessage(Handler.java:110)
                      at android.os.Looper.loop(Looper.java:203)
                      at android.app.ActivityThread.main(ActivityThread.java:6251)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
                   Caused by: java.lang.reflect.InvocationTargetException
E/AndroidRuntime:     at java.lang.reflect.Constructor.newInstance0(Native Method)
                      at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                      at android.support.v4.app.Fragment.instantiate(Fragment.java:459)
                        ... 34 more
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
                      at com.example.bengisu.bitirme.Board.<init>(Board.java:17)
                      at com.example.bengisu.bitirme.GameBoard.<init>(GameBoard.java:21)
                        ... 37 more
Application terminated.

我的抽象子类:Board.java

公共抽象类委员会扩展片段{

FragmentManager fm=((MainActivity)getActivity()).getSupportFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
public abstract void  Hide(Fragment fragment);
public abstract void Show(Fragment fragment);

}

First Fragment:GameBoard.java

public class GameBoard extends Board {

    TextView t[]=new TextView[10];
    TextView p[]=new TextView[3];
    static float maxX,maxY;
    Display mdispl;
    Rain rain[]=new Rain[10];
    Bucket bucket;
    ImageView imgB;
    ValueAnimator vaB;
    int s=0;



public GameBoard getGameBoard(){
    GameBoard gameBoard=(GameBoard) fm.findFragmentById(R.id.gameBoard);
    return gameBoard;
}

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_board, container, false);
        mdispl =getActivity().getWindowManager().getDefaultDisplay();
        maxX = mdispl.getWidth();
        maxY = mdispl.getHeight();

         fm=getActivity().getSupportFragmentManager();
         ft=fm.beginTransaction();

        t[0]=view.findViewById(R.id.t0);
        t[1] = view.findViewById(R.id.t1);
        t[2] = view.findViewById(R.id.t2);
        t[3] = view.findViewById(R.id.t3);
        t[4] = view.findViewById(R.id.t4);
        t[5] = view.findViewById(R.id.t5);
        t[6] = view.findViewById(R.id.t6);
        t[7] = view.findViewById(R.id.t7);
        t[8] = view.findViewById(R.id.t8);
        t[9] = view.findViewById(R.id.t9);
        p[0] = view.findViewById(R.id.p0);
        p[1] = view.findViewById(R.id.p1);
        p[2] = view.findViewById(R.id.p2);

        for (int i=0;i<10;i++){
            rain[i]=new Rain(maxX,maxY);
            rain[i].Move(t[i],0,0,5000);

        }


        imgB=view.findViewById(R.id.imageView);

        bucket= new Bucket(imgB);

        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                float initialX=event.getX();
                if(initialX>getActivity().getWindowManager().getDefaultDisplay().getWidth()/2){

                   vaB= bucket.Move(null,imgB.getX(),getActivity().getWindowManager().getDefaultDisplay().getWidth()-imgB.getWidth()+150,1850);
                }
                else{

                    vaB=bucket.Move(null,imgB.getX(),-250,1850);
                }
                return false;
            }
        });

        return view;
    }

    public void PauseBucket(){

        vaB.pause();
    }

@Override
    public void Hide(Fragment fragment) {
        ft.hide(fragment);
        ft.commitNow();
    }

@Override
    public void Show(Fragment fragment) {
       ft.show(fragment);
        ft.commitNow();
    }
}

Second Fragment:ScoreBoard.java

public class ScoreBoard extends Board{
    //FragmentManager fm;
    //FragmentTransaction ft;
    ScoreBoard scoreBoard;


    public ScoreBoard getScoreBoard(){
    scoreBoard=(ScoreBoard)fm.findFragmentById(R.id.scoreBoard);
    return scoreBoard;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        fm=getActivity().getSupportFragmentManager();
        ft=fm.beginTransaction();
        View view=inflater.inflate(fragment_score_board, container, false);

        return view;
    }

@Override
    public void Hide(Fragment fragment) {

        ft.hide(fragment);
        ft.commitNow();
    }

@Override
    public void Show(Fragment fragment) {

        ft.show(fragment);
        ft.commitNow();
    }
}

我的MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView time,Gscore,Sscore;
    FloatingActionButton repeat,pause,resume;
    GameBoard gameBoard;
    ScoreBoard scoreBoard;
    Bucket bucket;
    CountDownTimer timer;
    int score=0;
    String name;

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

        time = findViewById(R.id.time);
        Gscore = findViewById(R.id.score);
        Sscore = findViewById(R.id.Sscore);
        repeat= findViewById(R.id.repeat);
        pause = findViewById(R.id.pause);
        resume = findViewById(R.id.resume);
        gameBoard=gameBoard.getGameBoard();
        scoreBoard=scoreBoard.getScoreBoard();

        Game(60000,0);

        repeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               scoreBoard.Hide(scoreBoard);
               gameBoard.Show(gameBoard);
                Gscore.setVisibility(View.VISIBLE);
                //gameBoard.StartAgain();
                Game(60000,0);
               // flipper.showNext();
                bucket.bucket.setX(getWindowManager().getDefaultDisplay().getWidth()/2-100);
            }
        });
    }

    public void Game(long m,int s){

       //gameFragment.s=s;
        timer= new CountDownTimer(m,1000) {

            public void onTick(long millisUntilFinished) {
               scoreBoard.Hide(scoreBoard);
               gameBoard.Show(gameBoard);
               score = gameBoard.s;
                String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d",
                        (millisUntilFinished / 1000) / 60,
                        (millisUntilFinished / 1000) % 60);
                time.setText(""+timeLeftFormatted);
                Gscore.setText(""+score);
                if(millisUntilFinished<=30000){
                    time.setTextColor(Color.BLACK);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            time.setTextColor(Color.WHITE);
                        }
                    },500);

                }
                else time.setTextColor(Color.BLACK);
            }

            public void onFinish() {
                scoreBoard.Show(scoreBoard);
                gameBoard.Hide(gameBoard);
                //flipper.showNext();
                Gscore.setVisibility(View.INVISIBLE);
                Sscore.setText(name+"'s Score : "+Gscore.getText());

            }

        };

        timer.start();

    }




}

2 个答案:

答案 0 :(得分:1)

我不明白你的意思,但我在这一行中看到了一个问题

FragmentManager fm=((MainActivity)getActivity()).getSupportFragmentManager(); 

似乎getActivity()返回null,因此错误说:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentManager android.support.v4.app.FragmentActivity.getSupportFragmentManager()' on a null object reference
                  at com.example.bengisu.bitirme.Board.<init>(Board.java:17)
                  at com.example.bengisu.bitirme.GameBoard.<init>(GameBoard.java:21)

也许您应该尝试在onActivityCreated

中初始化此变量

答案 1 :(得分:0)

实例化片段存在问题。
还要跟踪显示的问题,看看你的MainActivity类的xml中的第0行

Unable to start activity   
  ComponentInfo{com.example.bengisu.bitirme/com.example.bengisu.bitirme.MainActivity
  }: android.view.InflateException: Binary XML file line #0: Binary XML file      
  line #0: Error inflating class fragment


这也不是实例化片段的正确方法 以下链接可以帮助您处理framents https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments

简而言之,你应该按照以下方式创建你的framgne:

 FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
 ft.replace(R.id.frame_layout, new YourFragment());
 // or ft.add(R.id.frame_layout, new FooFragment());
 ft.commit();