按一下按钮,清除EditText字段的内容

时间:2016-05-11 00:03:30

标签: android listview android-studio android-edittext android-handler

我正在创建一个简单的应用,一旦名为runAs的{​​{1}}字段的内容包含关键短语,该应用会自动触发按钮b。我希望在2秒后自动清除编辑文本字段的内容。有没有一种简单的方法可以将其实现到我的代码中?

EditText

由于使用布尔方法,如果我在我的应用程序中使用后退按钮等返回此活动,它似乎不会再次触发该选项。如果我回到同一个窗口/活动,有没有办法让它再次触发a

我真的很感激在修改上面显示的部分代码方面提供了一些有用的帮助。

1 个答案:

答案 0 :(得分:0)

对于第一部分,您实际上已在代码上执行此操作。我唯一不理解的是为什么你有boolean isDone?你试过删除它吗?如果您已经清除了EditText,即使它再次通过onTextChanged,它也不会再次通过第一个条件(这里我假设b的行为是清除a)的文字。

对于文本检查,我认为您可以使用androids TextUtils.equals()

TextUtils.equals(s, "open voice command");
  

修改

好。所以我重新分析了你的帖子和你的评论,最后得到了这种行为。

第一次活动开始时,当您输入"打开语音命令"在EditText a中,系统会自动点击Button b并继续开始活动,并且必须清除EditText a。回到包含EditText aButton b的活动,您希望EditText a onTextChangeListener仍然有效。

考虑到这些,我最终修改了你的代码如下:

public class MainActivity extends AppCompatActivity {

    EditText a;
    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Views
        a = (EditText) findViewById(R.id.a);
        b = (Button) findViewById(R.id.b);

        // Initialize listeners
        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 (TextUtils.equals(s, "open voice command")) {
                    Log.d("SAMPLE", ">>>>>>> Running handler!....");
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            a.setText(null);
                            b.performClick();
                        }
                    }, 500);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SampleActivity.class);
                startActivity(intent);
            }
        });

    }

}

当我输入&#34;打开语音命令&#34; EditText a中的performClick()会自动清除,并为Button b调用EditText a。我回到活动后。没有任何事情发生,处理程序无法运行,因为import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.speech.RecognitionListener; import android.speech.SpeechRecognizer; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; import java.util.HashMap; 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; Boolean isDone = false; @Override public void onCreate(Bundle state) { super.onCreate(state); setContentView(R.layout.activity_main); // Prepare the data for UI // captions = new HashMap<String, Integer>(); // captions.put(KWS_SEARCH, R.string.kws_caption); // ((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.a); b = (Button) findViewById(R.id.b); // 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(); //line added...///////////////////////// 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) { } }); //////////////////////////////////////// } @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(); // } // } /** * 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.b) { 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 'command' which is not case sensitive if (str_1.toLowerCase().contains("command")) { Intent userintent = new Intent(PocketSphinxActivity.this, Gvoice.class); startActivity(userintent); } else { Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show(); } } } //Added this to clear the 'open voice command' text when pressing back from a activity window //This at the moment seems to only work when typing the command, If I use speech to text to say'open voice command @Override public void onResume() { super.onResume(); isDone = false; a.setText(""); } } 的文本值为空。如果您输入&#34;打开语音命令&#34;。

,处理程序将仅再次触发
  

编辑2

这是我正在运行的代码。我刚刚评论了大部分与您帖子中的问题无关的代码。我得到了你正在瞄准的正确行为。

wp_register_script( 'jquery-cookie', get_template_directory_uri() . '/vendor/js/js.cookie.js', array( 'jquery' ) );
wp_enqueue_script( 'jquery-cookie' );