为什么这个计时器不会在我的片段中执行?

时间:2017-10-23 21:40:48

标签: java android android-fragments

问题陈述了为什么这个计时器没有执行?我把它设置在片段中,我觉得它与我的runOnUiThread有关,但我不确定。此外,我应该补充说,我没有得到任何错误或任何它不会执行。

final WeakReference<Activity> activityRef = new WeakReference<Activity>((getActivity()));
    //creating timer
    public void startRandomButton(final ImageView img)
    {
        Timer timer = new Timer();
        timer.schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            if(activityRef.get() == null)
                return;

                //activityRef.get().runOnUiThread(new Runnable()
            if(isAdded())
            {
                activityRef.get().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Activity activity = activityRef.get();
                        if (isAdded())
                            randomMovement(img);
                        else
                            Log.d("not added", "not added");
                    }
                });
            }
            else
                Log.d("Run on ui thread", "is null");
        }
    }, 5000);
}

下面是我创建计时器时出现问题的整个片段。就像我在原始问题中说的那样,我不确定问题是什么。代码编译并执行得很好。计时器方法虽然不会工作。我有我的日志猫告诉我什么时候一个活动被破坏或者当你经历这个时你会看到我告诉我哪里的东西是空的而且我没有得到任何错误。非常感谢帮助!:

package com.example.name.inserttitlename;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import android.view.InflateException;

import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;

import static android.R.attr.x;


/**
 * A simple {@link Fragment} subclass.
 */
public class LevelOneFragment extends Fragment {

    //creating variables
    private ImageView img;
    private ViewGroup viewer;
    TextView textCount;
    Button failButton;
    Button beginButton;
    TextView countDownBeginText;
    private TextView countDownMain;
    public int scoreCounter;

    public LevelOneFragment() {
        // Required empty public constructor
    }

     @Override
     public void onAttach(Context context)
     {
       super.onAttach(context);
       Activity a;

       if(context instanceof Activity)
       {
          a=(Activity) context;
       }

     }

     @Override
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
     }



    @Override
    public  View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment



        View view = inflater.inflate(R.layout.fragment_level_one, container, false);

        //creating viewables and such
        viewer = (ViewGroup) view.findViewById(R.id.view_level);
        img = (ImageView) view.findViewById(R.id.imageView);
        failButton = (Button) view.findViewById(R.id.failureButton);
        countDownMain = (TextView) view.findViewById(R.id.countDownMain);
        countDownBeginText = (TextView) view.findViewById(R.id.countDownBeginText);
        beginButton = (Button) view.findViewById(R.id.beginButton);


        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(150, 150);
        img.setLayoutParams(layoutParams);
        img.setOnTouchListener(new LevelOneFragment.ChoiceTouchListener());

        //begin random movement

           startRandomButton(img);


        //setting up button for failure CORRECT TO TAKE YOU TO THE MAIN MENU
        failButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                startActivity(new Intent(getActivity(), MainMenu.class));
            }
        });


        //setting countdown text to 3
        countDownBeginText.setText(":3");

        //begin countdown from three
        beginButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View beginT) {
                CountDownTimer countDownTimer = new CountDownTimer(3*1000, 3) {
                    @Override
                    public void onTick(long millisUntilFinished) {

                        countDownBeginText.setText(":" + millisUntilFinished/1000);
                        //add possible sound here every tick
                    }

                    @Override
                    public void onFinish() {
                        beginButton.setVisibility(View.INVISIBLE);
                        countDownBeginText.setVisibility(View.INVISIBLE);

                        //countdown from 60------- change parameters in count down timer to the time desired
                        CountDownTimer countDownTimer = new CountDownTimer(60*1000, 3) {
                            @Override
                            public void onTick(long millisUntilFinishedMain) {

                                countDownMain.setText(":" + millisUntilFinishedMain/1000);
                                //add possible sound here every tick
                            }

                            @Override
                            public void onFinish() {
                                //Toast.makeText(getActivity(),"You lose", Toast.LENGTH_LONG).show();
                                //rest of text in method is trial

                                startActivity(new Intent(getActivity(), MainMenu.class ));

                            }
                        }.start();

                    }
                }.start();
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstatnceCState)
    {
        super.onActivityCreated(savedInstatnceCState);
    }

    //getting screen size
    public static Point getDisplaySize(@NonNull Context context){

        Point point = new Point();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getSize(point);
        return point;
    }

    //randomly move

    public void randomMovement(ImageView img){

            int x = new Random().nextInt(getDisplaySize(getActivity()).x);
            int y = new Random().nextInt(getDisplaySize(getActivity()).y);
            img.setY(y);
            img.setX(x);


    }


    final WeakReference<Activity> activityRef = new WeakReference<Activity>((getActivity()));
    //creating timer
    public void startRandomButton(final ImageView img)
    {
        Timer timer = new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                if(activityRef.get() == null)
                    return;

                    //activityRef.get().runOnUiThread(new Runnable()
                if(isAdded())
                {
                    activityRef.get().runOnUiThread(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            Activity activity = activityRef.get();

                            if (isAdded())
                                randomMovement(img);
                            else
                                Log.d("not added", "not added");
                        }
                    });
                }
                else
                    Log.d("Run on ui thread", "is null");
            }
        }, 5000);
    }

    //listener for the moving ball
    private final class ChoiceTouchListener implements View.OnTouchListener {
        public boolean onTouch(View view, MotionEvent event){

            //Calling Counter
            textCount = (TextView) getView().findViewById(R.id.textViewCount);



            //switch statement for different events
            switch (event.getAction() & MotionEvent.ACTION_MASK){

                case MotionEvent.ACTION_DOWN:
                    break;

                case MotionEvent.ACTION_UP:
                    //this is where youre going to generate randmom location with id.setX(randomX) and id.setY(randomY)
                    randomMovement(img);

                    //Setting Counter to count when img is clicked
                    String countValue = textCount.getText().toString();
                    scoreCounter = Integer.parseInt(countValue);
                    scoreCounter++;
                    textCount.setText(String.valueOf(scoreCounter));
                    break;


                case MotionEvent.ACTION_POINTER_DOWN:
                    break;

                case MotionEvent.ACTION_POINTER_UP:
                    break;


            }



            //checking score
            if(scoreCounter == 10 )
            {
                Toast.makeText(getActivity(),"You win", Toast.LENGTH_LONG).show();

            }

            viewer.invalidate();
            return true;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在课程的其他部分,你也有一些代码也不清楚。所以这里是片段的代码:

#!/bin/bash

count=$(xmllint --xpath "count(//programme)" /tmp/file.xml)

for ((i=1; i<=count; i++)); do
    xmllint --xpath "//programme[$i]/title/text()" /tmp/file.xml
    echo -n '|'
    xmllint --xpath "//programme[$i]/sub-title/text()" /tmp/file.xml
    echo
done

我还没有对代码进行测试,因此可能存在细微的错误。