Android更新textview计时器和刷新地图内容?

时间:2017-02-12 16:37:46

标签: android google-maps timer

我有以下布局文件。基本上我有谷歌地图,在左上角我有TextView我需要保持计数器说每15秒刷新一次地图。布局很好。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context="com.example.ns.appversion1.MapActivityFragment1"
    android:name="com.google.android.gms.maps.SupportMapFragment"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:weightSum="2" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="left"
                android:padding="3dp"
                android:id="@+id/textRefresh"
                android:background="@drawable/border"
                android:text="Refreshing 1"
                android:textColor="#03A9FA"
                android:textSize="12sp" />


        </LinearLayout>
    </FrameLayout>
 </RelativeLayout>

以下是我的代码。在视图函数中,我尝试实现Handler函数来保持计数器。因此,每隔15秒,我想调用JSON函数来检索最新的lat long值并相应地在地图上绘图。我现在停留在这里的第一步,它给出了我在内部类中无法访问变量timeleftm_handlerTaskm_handler的错误?我想显示倒计时,以便用户在接下来的15秒钟内知道地图会刷新吗?

public class MapActivityFragment1 extends Fragment implements OnMapReadyCallback  {
    private GoogleMap mMap;
    TextView tv;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    // TODO: Rename and change types and number of parameters
    public static MapActivityFragment1 newInstance(String param1, String param2) {
        MapActivityFragment1 fragment = new MapActivityFragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map_activity_fragment1, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        tv = (TextView) getActivity().findViewById(R.id.textRefresh);
        Handler m_handler;
        Runnable m_handlerTask ;
        final int timeleft=15000;
        final m_handler = new Handler();
        final m_handlerTask = new Runnable()
        {
            @Override
            public void run() {
                if(timeleft>=0)
                {
                    // do stuff
                    Log.i("timeleft",""+timeleft);
                    timeleft--;
                    tv.setText("Refreshing in "+timeleft);

                }
                else
                {
                    m_handler.removeCallbacks(m_handlerTask); // cancel run
                }
                m_handler.postDelayed(m_handlerTask, 1000);
            }
        };
        m_handlerTask.run();

        return view;
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

我尝试过Charu的解决方案如下。

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_map_activity_fragment1, null, false);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        tv = (TextView) getActivity().findViewById(R.id.textRefresh);
        MyCount counter = new MyCount(15000, 1000);
        counter.start();

        return view;
    }

2 个答案:

答案 0 :(得分:1)

这将演示从15到0的倒计时(-1秒),此任务将在每15秒后重复一次!

    public class YourActivity extends Activity {


    TextView textView;
    android.os.Handler customHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        textView = (TextView) findViewById(R.id.text);


        customHandler = new android.os.Handler();
        customHandler.postDelayed(updateTimerThread, 0);
    }


    // count down timer is an abstract class, so extend it and fill in methods
    public class MyCount extends CountDownTimer {

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

        @Override
        public void onFinish() {
            textView.setText("done!");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            textView.setText("Left: " + millisUntilFinished / 1000);
        }
    }

    private Runnable updateTimerThread = new Runnable()
    {
        public void run()
        {

            // 10000 is the starting number (in milliseconds)
            // 1000 is the number to count down each time (in milliseconds)
            MyCount counter = new MyCount(15000, 1000);
            counter.start();
            customHandler.postDelayed(this, 15000); // repeat body after  15 seconds
        }
    };
}

答案 1 :(得分:0)

只是一个建议。

据我所知,处理程序在主线程上运行,因此,一旦此线程负责所有UI交互,请尝试使用轻量级处理任务。如果您需要处理大量数据或需要一些时间(例如,等待服务器的响应),建议您使用另一个线程,例如使用异步任务或协程。

我个人喜欢同时使用两者。我使用处理程序来创建此事件,现在是时候这样做了,我调用了在另一个线程中运行的函数来完成它。