【问题标题】:Two actions with one button android一键实现两个动作 android
【发布时间】:2013-10-08 12:25:51
【问题描述】:

我有这个问题,我想在单击按钮时启动一个活动。我已经完成了,但是当我开始新的活动时,我也想同时停止振动器,这样当旧的活动继续时,我希望振动器停止。我的代码:

package com.edae;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Btcom extends Activity implements OnClickListener {
 private Button bokay;
 Vibrator vibe;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_btcom);
    bokay = (Button) this.findViewById(R.id.okay);
    bokay.setOnClickListener(this);
    final Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    int dot = 2000;
    long patten[] = {0, dot };
    vibe.vibrate(patten, -1);
    }

@Override
public void onClick(View v){
    Intent openBoot = new Intent(this, Boot.class);
    startActivity(openBoot);
    super.onPause();
  }
}

【问题讨论】:

  • 覆盖onPause()方法并在那里停止振动器,也不需要在onClick()方法中调用onPause()
  • 啊,原因.. 这很明显.. 很抱歉浪费了您和其他人的时间.. 我的错。

标签: android button android-activity action


【解决方案1】:

您的代码中有一个小错误。您已在 onCreate 中重新声明了 vibe
先替换

final Vibrator vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

vibe = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

并声明你的全局变量vibefinal

然后你可以这样解决你的问题:

@Override
public void onClick(View v){
    Intent openBoot = new Intent(this, Boot.class);
    vibe.cancel();
    startActivity(openBoot);
  }
}

这里不需要super.onPause(),因为startActivity(openBoot) 会自动暂停您的活动。

【讨论】:

    【解决方案2】:
    public void onClick(View v){
    Intent openBoot = new Intent(this, Boot.class);
    startActivity(openBoot);
    //stop your vibrator here.
    super.onPause();
    

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多