如果 EditText 正确则自动点击 Button

Automatically click Button if EditText is correct

我正在创建一个简单的应用程序,如果 EditText 字段包含正确的信息,我需要一个名为 'bVoice' 的按钮在 500 毫秒后自动按下。

如何在以下代码中编写处理程序来执行此操作:

//Assign button clicks to got to a new activity:
public void onButtonClick_1(View v){
    if (v.getId() == R.id.bVoice){
        String str_1 = a.getText().toString();

        //Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'next' which is not case sensitive
        if (str_1.toLowerCase().contains("command")) {
            Intent userintent = new Intent(PocketSphinxActivity.this, Display_1.class);
            startActivity(userintent);
        } else {
            Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
        }
    }
}

以下是我目前获得的完整代码(已更新):

public class PocketSphinxActivity extends Activity implements RecognitionListener
{

private static final String KWS_SEARCH = "wakeup";

/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "open voice command";   //adjust this keyphrase!

private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;

ListView lv;
TextView tv;
EditText a;
Button b;
Button c;

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);

    // Prepare the data for UI
    captions = new HashMap<String, Integer>();
    captions.put(KWS_SEARCH, R.string.kws_caption);
    setContentView(R.layout.main);
    ((TextView) findViewById(R.id.caption_text))
            .setText("Preparing the recognizer");

    lv = (ListView) findViewById(R.id.lvVoiceReturn);
    tv = (TextView) findViewById(R.id.result_text);
    a = (EditText) findViewById(R.id.TFusername);
    b = (Button) findViewById(R.id.bVoice);
    c = (Button)findViewById(R.id.Blogin);

    // Recognizer initialization is a time-consuming and it involves IO,
    // so we execute it in async task

    new AsyncTask<Void, Void, Exception>() {
        @Override
        protected Exception doInBackground(Void... params) {
            try {
                Assets assets = new Assets(PocketSphinxActivity.this);
                File assetDir = assets.syncAssets();
                setupRecognizer(assetDir);
            } catch (IOException e) {
                return e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Exception result) {
            if (result != null) {
                ((TextView) findViewById(R.id.caption_text))
                        .setText("Failed to init recognizer " + result);
            } else {
                switchSearch(KWS_SEARCH);
            }
        }
    }.execute();
    a.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().trim().equalsIgnoreCase("open voice command")) {
                //
                //Do your stuff here OR button.performClick()
                //

                //DELAY
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        b.performClick();
                    }
                }, 500);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
}

@Override
public void onDestroy() {
    super.onDestroy();
    recognizer.cancel();
    recognizer.shutdown();
}

/**
 * In partial result we get quick updates about current hypothesis. In
 * keyword spotting mode we can react here, in other modes we need to wait
 * for final result in onResult.
 */
@Override
public void onPartialResult(Hypothesis hypothesis) {
    if (hypothesis == null)
        return;

    String text = hypothesis.getHypstr();
    //((TextView) findViewById(R.id.result_text)).setText(text);
    ((EditText) findViewById(R.id.TFusername)).setText(text);
}

/**
 * This callback is called when we stop the recognizer.
 */
@Override
public void onResult(Hypothesis hypothesis) {
    //((TextView) findViewById(R.id.result_text)).setText("");
    ((EditText) findViewById(R.id.TFusername)).setText("");
    if (hypothesis != null) {
        String text = hypothesis.getHypstr();
        makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();


    //a.setText((String) tv.getText());
        //tv = TextView.getText().toString();
    }
}

@Override
public void onBeginningOfSpeech() {
}

/**
 * We stop recognizer here to get a final result
 */
@Override
public void onEndOfSpeech() {
    if (!recognizer.getSearchName().equals(KWS_SEARCH))
        switchSearch(KWS_SEARCH);
}

private void switchSearch(String searchName) {
    recognizer.stop();

    // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
    if (searchName.equals(KWS_SEARCH))
        recognizer.startListening(searchName);
    else
        recognizer.startListening(searchName, 10000);

    String caption = getResources().getString(captions.get(searchName));
    ((TextView) findViewById(R.id.caption_text)).setText(caption);
}

private void setupRecognizer(File assetsDir) throws IOException {
    // The recognizer can be configured to perform multiple searches
    // of different kind and switch between them

    recognizer = defaultSetup()
            .setAcousticModel(new File(assetsDir, "en-us-ptm"))
            .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))

                    // To disable logging of raw audio comment out this call (takes a lot of space on the device)
            .setRawLogDir(assetsDir)

                    // Threshold to tune for keyphrase to balance between false alarms and misses
            .setKeywordThreshold(1e-45f)

                    // Use context-independent phonetic search, context-dependent is too slow for mobile
            .setBoolean("-allphone_ci", true)

            .getRecognizer();
    recognizer.addListener(this);

    /** In your application you might not need to add all those searches.
     * They are added here for demonstration. You can leave just one.
     */

    // Create keyword-activation search.
    recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);

}

@Override
public void onError(Exception error) {
    ((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}

@Override
public void onTimeout() {
    switchSearch(KWS_SEARCH);
}

//Assign button clicks to go to a new activity:
public void onButtonClick_1(View v){
    if (v.getId() == R.id.bVoice){
        String str_1 = a.getText().toString();
}

代码底部带有 onResume 的更新文本:

    @Override
public void onResume(){
    super.onResume();
    isDone = false;
    a.setText("");
}

如果你想根据编辑文本中的输入做一些事情,那么你可以使用 TextWatcher。

更新 创建全局布尔变量:

Boolean isDone=false;

然后在您的处理程序代码中像这样更新代码:

a.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().trim().equalsIgnoreCase("open voice command"))
            {
                //
                //Do your stuff here OR button.performClick()
                //

                //DELAY
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isDone){
                            b.performClick();
                            isDone=true;
                        }                        }
                }, 500);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

只需在 AsyncTask 之后添加此代码。即在

之后
}.execute();

要导入 Editable class,单击它并按 alt+Enter。 对 TextWatcher 执行相同操作,单击它,然后按 alt+Enter。

只要 EditText 中的文本发生变化,您在 onTextChanged 中键入的任何代码都会被执行。解决您的自动问题。