关于片段替换的findViewById的NullPointerException

时间:2016-01-08 04:34:40

标签: android android-fragments nullpointerexception

我有一项活动,比如A,其中有一个片段,其中包含一个名为TotalTimerFragment的文字视图,其中包含countdowntimer。还有另外两个名为F1F2的片段。活动A会添加F1,片段countdowntimer中的TotalTimerFragment会启动。几秒钟后,F1F2取代。在这里countdowntimer应该继续几秒钟。但它崩溃并在类中的OnTick方法中为findViewById提供NullPointerException

以下是FT片段的代码:getActivity().findViewById(R.id.total_timer_textview)方法中的onTick给出了NullPointerException

public class TotalTimerFragment extends Fragment{
    TextView totalWorkoutTimer;
    TotalTimeCounter timeCounter;
    static long total_millis;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_totaltimer, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        totalWorkoutTimer = (TextView) getActivity().findViewById(R.id.total_timer_textview);
    }

    public class TotalTimeCounter extends CountDownTimer {
        TextView totalWorkoutTimer;

        public TotalTimeCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            total_millis = millisUntilFinished;
            String total_hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(total_millis),
                    TimeUnit.MILLISECONDS.toMinutes(total_millis) - TimeUnit.HOURS.toMinutes(TimeUnit.
                        MILLISECONDS.toHours(total_millis)), TimeUnit.MILLISECONDS.toSeconds(total_millis) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(total_millis)));
            totalWorkoutTimer = (TextView)getActivity().findViewById(R.id.total_timer_textview);
            totalWorkoutTimer.setText(total_hms);
        }

        @Override
        public void onFinish() {

        }
    }
}

3 个答案:

答案 0 :(得分:3)

下面:

  

totalWorkoutTimer =(TextView)   。getActivity()findViewById(R.id.total_timer_textview);

导致问题,因为total_timer_textview TextView位于Fragment布局中,但访问了返回Activity上下文的getActivity()方法。

使用view方法的onViewCreated第一个参数,如:

totalWorkoutTimer = (TextView)view.findViewById(R.id.total_timer_textview);

答案 1 :(得分:1)

如果您在布局中使用片段和textview,则应使用if ($_SESSION['popup']==1){ ?> <script> $(function() { $( "#dialog" ).dialog({ width : 710, height : 410, modal: true, resizable: false, draggable: false, }); </script> <?php $_SESSION['popup']==NULL; } 代替view

getActivity()

似乎你没有调用计时器类,你可以试试这个

totalWorkoutTimer = (TextView) view.findViewById(R.id.total_timer_textview);

答案 2 :(得分:1)

您必须在片段xml文件中使用id为total_timer_textview的textview