Android中10秒后隐藏布局?

use*_*362 13 android

我点击按钮时会显示一个布局.我希望在10秒后隐藏该布局.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mVolHandler = new Handler();
    mVolRunnable = new Runnable() {
        public void run() {
            mVolLayout.setVisibility(View.GONE);
        }
    };
}


private OnTouchListener mVolPlusOnTouchListener = new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mVolLayout.setVisibility(View.VISIBLE);
        mVolHandler.postDelayed(mVolRunnable, 10000);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kar*_*iya 37

利用Handler&Runnable.

您可以使用postDelayedHandler 延迟Runnable .

Runnable mRunnable;
Handler mHandler=new Handler();

mRunnable=new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                yourLayoutObject.setVisibility(View.INVISIBLE); //If you want just hide the View. But it will retain space occupied by the View.
                yourLayoutObject.setVisibility(View.GONE); //This will remove the View. and free s the space occupied by the View    
            }
        };
Run Code Online (Sandbox Code Playgroud)

现在在onButtonClick事件中你必须告诉Handler在X毫秒后运行一个runnable:

mHandler.postDelayed(mRunnable,10*1000);
Run Code Online (Sandbox Code Playgroud)

如果你想取消这个,你必须使用 mHandler.removeCallbacks(mRunnable);

更新(根据编辑的问题) 您只需要删除Handler使用回调removeCallbacks()

所以只需在onTouch方法内更新代码,如下所示:

mVolLayout.setVisibility(View.VISIBLE);
mVolHandler.removeCallbacks(mVolRunnable);
mVolHandler.postDelayed(mVolRunnable, 10000);
Run Code Online (Sandbox Code Playgroud)