为我的应用启用和禁用系统键盘

时间:2018-11-30 07:15:19

标签: android android-studio keyboard-events morse-code

这是一个莫尔斯电码应用程序,可将莫尔斯电码转换为字母,再将字母转换为莫尔斯电。为此,我创建了自己的键盘。为了显示和隐藏此键盘和系统键盘,我使用了对我而言无法正常工作的代码。

 package com.aswdc_morsecode.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.EditText;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.aswdc_morsecode.R;

public class MainActivity extends AppCompatActivity {

    boolean isAlphaMorse = true;

    private TextView tvConvert;
    private TextView tvResult;
    private Button btnToMorse;
    private Button btnToAlpha;


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

//键盘方法从此处开始

        EditText editText = (EditText) findViewById(R.id.main_et_convert);
        MyKeyboard keyboard = (MyKeyboard) findViewById(R.id.keyboard1);

//下面几行用于启用和禁用系统键盘

        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
        editText.setTextIsSelectable(true);

        InputConnection ic = editText.onCreateInputConnection(new EditorInfo());
        keyboard.setInputConnection(ic);
        keyboard.setVisibility(View.GONE);


        tvConvert = (TextView) findViewById(R.id.main_et_convert);
        tvResult = (TextView) findViewById(R.id.main_tv_result);
        btnToMorse = (Button) findViewById(R.id.main_btn_toMorse);

//其余代码

        btnToMorse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAlphaMorse = !isAlphaMorse;
                MyKeyboard keyboard = (MyKeyboard) findViewById(R.id.keyboard1);
                keyboard.setVisibility(isAlphaMorse?View.GONE:View.VISIBLE);
            }
        });
        editText.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 (isAlphaMorse) {
                    String txtToConvert = tvConvert.getText().toString();
                    String convertedTxt = MorseCode.alphaToMorse(txtToConvert);
                    tvResult.setText(convertedTxt);
                } else {
                    String txtToConvert = tvConvert.getText().toString();
                    String convertedTxt = MorseCode.morseToAlpha(txtToConvert);
                    tvResult.setText(convertedTxt);
                }
            }

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

0 个答案:

没有答案