runOnUiThread in fragment

前端 未结 6 572
囚心锁ツ
囚心锁ツ 2020-11-30 21:49

I\'m trying to convert an Activity to fragment. The error mark on runOnUiThread. on the past:

GoogleActivityV2 extends from Activity. ru

6条回答
  •  孤城傲影
    2020-11-30 22:02

    I used this for getting Date and Time in a fragment.

    private Handler mHandler = new Handler(Looper.getMainLooper());
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
    
        dateTextView =  root.findViewById(R.id.dateView);
        hourTv = root.findViewById(R.id.hourView);
    
            Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(1000);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                //Calendario para obtener fecha & hora
                                Date currentTime = Calendar.getInstance().getTime();
                                SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                                SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
    
                                String currentDate = date_sdf.format(currentTime);
                                String currentHour = hour_sdf.format(currentTime);
    
                                dateTextView.setText(currentDate);
                                hourTv.setText(currentHour);
                            }
                        });
                    }
                } catch (InterruptedException e) {
                    Log.v("InterruptedException", e.getMessage());
                }
            }
        };
    }
    

提交回复
热议问题