package com.example.a03.gotostudy; import android.os.Handler; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.Timer; import java.util.TimerTask; public class StudyActivity extends AppCompatActivity implements View.OnClickListener { private Button pre,next,back; private TextView show; private int index; private final String[] contents = {"1","2","3","4","5","6"}; private Handler mHandler; private final int INTERVAL_TIME = 5000; private Runnable mRunnable = new Runnable() { @Override public void run() { updateContent(); mHandler.postDelayed(mRunnable,INTERVAL_TIME); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_study); init(); } public void init() { pre = findViewById(R.id.pre); next = findViewById(R.id.next); show = findViewById(R.id.show); back = findViewById(R.id.back); pre.setOnClickListener(this); next.setOnClickListener(this); back.setOnClickListener(this); index = 0; mHandler = new Handler(); mHandler.post(mRunnable); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.pre: pre(); break; case R.id.next: next(); break; case R.id.back: finish(); break; } } public void updateContent(){ show.setText(contents[index]); } public void pre(){ if ((index-1)<0){ index = contents.length-1; } else { index--; } updateContent(); } public void next(){ if ((index+1)>contents.length-1){ index=0; } else{ index++; } updateContent(); } @Override protected void onDestroy() { super.onDestroy(); mHandler.removeCallbacks(mRunnable); } }这段代码有什么问题?
时间: 2024-02-15 12:28:55 浏览: 86
用于托管 Discord Overlay 的 DirectX 11 窗口.zip
这段代码看起来没有明显的问题,但是在使用 Handler.postDelayed() 方法时需要注意,如果在 Activity.onDestroy() 方法中没有移除该 Handler,可能会导致内存泄漏问题。在这段代码中,已经在 onDestroy() 方法中移除了 Handler,所以可以放心使用。
阅读全文