簡體   English   中英

按下按鈕后清除 EditText 字段的內容

[英]Clear the contents of an EditText Field once button is pressed

我正在創建一個簡單的應用程序,一旦名為aEditText字段的內容包含一個關鍵短語,它就會自動觸發按鈕b 我想在 2 秒后自動清除編輯文本字段的內容。 有沒有一種簡單的方法可以將其實現到我下面的代碼中?

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);

    // 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();
//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();
    }
}

@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();

        //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("");
}

}

此外,由於使用了布爾方法,如果我使用應用程序中的后退按鈕等返回此活動,它似乎不會再次觸發該選項。 如果我返回到同一個窗口/活動,有沒有辦法讓它再次觸發b

在修改上面顯示的部分代碼時,我將非常感謝一些有用的幫助。

對於第一部分,您實際上已經在您的代碼上這樣做了。 我唯一不明白的是為什么你有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);
            }
        });

    }

}

當我在EditText a輸入“打開語音命令”時,它會自動被清除並為Button b調用performClick() 在我回到活動之后。 沒有任何反應,處理程序不會運行,因為EditText a的文本值為空。 如果您輸入“打開語音命令”,處理程序只會再次觸發。

編輯 2

這是我正在運行的代碼。 我只是注釋掉了大部分與您帖子中關注的問題無關的代碼。 我得到了你想要的正確行為。

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("");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM