为什么GestureDetector无法正常运作?

时间:2018-11-16 13:01:52

标签: android android-studio

我想在两次触摸屏幕后设置“ inputVoice()”。例如,当我执行应用程序,然后两次触摸屏幕后,我想进行语音输入。所以我做到了,

@Override
public boolean onDoubleTap(MotionEvent e) {
inputVoice(); 
return super.onDoubleTap(e); }

但是当我执行应用程序时,它不起作用。它不起作用,包括GestureDectector和inputVoice。这是完整的代码和xml。我不知道怎么了。

public class CategoryActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
android.app.FragmentManager manager = getFragmentManager();
private GestureDetector mGestureDetector;
TextToSpeech tts;



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

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 5);

    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
    actionBar.setDisplayHomeAsUpEnabled(true);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    manager.beginTransaction().add(R.id.fragment_container, new Search()).commit();
    tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            tts.setLanguage( Locale.KOREAN);
            if (status == TextToSpeech.SUCCESS) {
                tts.speak( "다음은 상품 상세 페이지입니다. 원하시는 상품을 이야기해주세요" , TextToSpeech.QUEUE_FLUSH , null );

            }
        }
    });

    mGestureDetector = new GestureDetector(this, mOnSimpleOnGestureListener);
  //  inputVoice();

    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @SuppressLint("WrongConstant")
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            menuItem.setChecked(true);
            mDrawerLayout.closeDrawers();

            int id = menuItem.getItemId();

            switch (id) {
                case R.id.navigation_item_drink:
                    manager.beginTransaction().replace(R.id.fragment_container, new FirstItemFragment()).commit();
                    Toast.makeText(CategoryActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
                    break;

                case R.id.navigation_item_meat:
                    manager.beginTransaction().replace(R.id.fragment_container, new SecondItemFragment()).commit();
                    Toast.makeText(CategoryActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
                    break;

                case R.id.navigation_item_dairy_product:
                    manager.beginTransaction().replace(R.id.fragment_container, new ThirdItemFragment()).commit();
                    Toast.makeText(CategoryActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
                    break;

                case R.id.navigation_item_processed_food:
                    manager.beginTransaction().replace(R.id.fragment_container, new FourthItemFragment()).commit();
                    Toast.makeText(CategoryActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
                    break;

                case R.id.navigation_item_vegetable:
                    manager.beginTransaction().replace(R.id.fragment_container, new FifthItemFragment()).commit();
                    Toast.makeText(CategoryActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();
                    break;

            }

            return true;
        }
    });

}

public MenuItem searchItem;

public SearchView searchView;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    searchItem = menu.findItem(R.id.action_search);



    searchView = (SearchView) searchItem.getActionView();

    searchView.onActionViewExpanded(); // 바로 검색창 활성화

    searchView.setQueryHint("검색");


    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){

        @Override
        public boolean onQueryTextSubmit(String s) {
            InputMethodManager imm= (InputMethodManager) CategoryActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
            searchView.setQuery("", false);
            searchView.setIconified(true);

            manager.beginTransaction().replace(R.id.fragment_container, new Search(s)).commit();
            Toast.makeText(CategoryActivity.this, "search 결과 :" +s, Toast.LENGTH_LONG).show();
            return false;

        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
        case android.R.id.home:
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
        case R.id.action_settings:
            return true;
    }
    return super.onOptionsItemSelected(item);
}


@Override public boolean onTouchEvent(MotionEvent event) {
    // 여기에서는 터치 이벤트를 넘겨주어서 받고 난후, 리턴값을 돌려준다.
    // 일반 뷰에 붙여도 된다.
    return mGestureDetector.onTouchEvent(event);
}
private GestureDetector.SimpleOnGestureListener mOnSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {
    }
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        Toast.makeText(getBaseContext(), "녹음시작", Toast.LENGTH_SHORT).show();
    }

    @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {
        inputVoice();
        return super.onDoubleTap(e);
    }

    @Override
    public boolean onDoubleTapEvent(MotionEvent e) {
        return super.onDoubleTapEvent(e);
    }

    @Override

    public boolean onSingleTapConfirmed(MotionEvent e) {
        return super.onSingleTapConfirmed(e); }
};


public void inputVoice() {
    try {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra( RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");
        final SpeechRecognizer stt = SpeechRecognizer.createSpeechRecognizer(this);
        stt.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle params) {
                toast("음성 입력 시작...");
            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float rmsdB) {

            }

            @Override
            public void onBufferReceived(byte[] buffer) {
            }

            @Override
            public void onEndOfSpeech() {
                toast("음성 입력 종료");
            }

            @Override
            public void onError(int error) {
                toast("오류 발생 : " + error);
            }

            @Override
            public void onResults(Bundle results) {
                ArrayList<String> result = (ArrayList<String>) results.get(SpeechRecognizer.RESULTS_RECOGNITION);
                manager.beginTransaction().replace(R.id.fragment_container, new Search(result.get(0))).commit();
                replyAnswer(result.get(0));
                stt.destroy();
            }

            @Override
            public void onPartialResults(Bundle partialResults) {

            }

            @Override
            public void onEvent(int eventType, Bundle params) {

            }
        });
        stt.startListening(intent);
    } catch (Exception e) {
        toast(e.toString());
    }
}

public void replyAnswer(String input){
    try{tts.speak( input + " 검색결과입니다." , TextToSpeech.QUEUE_FLUSH , null );


    } catch (Exception e) {
        toast(e.toString());
    }
}

private void toast(String msg){
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}

}

和xml代码

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimaryDark"
            android:theme="@style/ThemeOverlay.AppCompat.Dark" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/notice_search_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="?android:attr/actionBarSize"
            android:layout_below="@id/toolbar"/>

    </FrameLayout>
</RelativeLayout>


<android.support.design.widget.NavigationView
    android:id="@+id/navigation_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    app:headerLayout="@layout/drawer_header"
    app:theme="@style/NavigationDrawerStyle"
    app:menu="@menu/drawer"/>

请帮助我任何可以解决的人。谢谢。

0 个答案:

没有答案