안 드 로 이 드 모방 위 챗 디지털 키보드
 2.고려 해 야 할 문제
레이아웃 의 실현 방식;
demo 에 서 는 popupwindow 를 사용 하여 xml 파일 을 통 해 Tablayot 레이아웃 을 진행 합 니 다.
EditText 기본 소프트 키보드 의 팝 업 을 금지 하고 사용자 정의 디지털 키보드 와 다른 EditText 와 초점 을 바 꿀 때의 팝 업 효과 로 바 꿉 니 다.
문 자 를 삭제 하고 추가 할 때 커서 의 위 치 를 동기 화해 야 합 니 다.
무 작위 디지털 분포 의 실현;
3.실현 코드
1.MainActivity 호출 부 코드:
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private EditText numberEt;
    private KeyboardPopupWindow keyboardPopupWindow;
    private boolean isUiCreated = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        numberEt = findViewById(R.id.numberEt);
        keyboardPopupWindow = new KeyboardPopupWindow(MainActivity.this, getWindow().getDecorView(), numberEt,true);
//        numberEt.setInputType(InputType.TYPE_NULL);//           
        numberEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (keyboardPopupWindow != null) {
                    keyboardPopupWindow.show();
                }
            }
        });
        numberEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (keyboardPopupWindow != null && isUiCreated) {//isUiCreated    ,Unable to add window -- token null is not valid; is your activity running?
                    keyboardPopupWindow.refreshKeyboardOutSideTouchable(!hasFocus);//                         
                }
                if (hasFocus) {//       
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(numberEt.getWindowToken(), 0);
                }
            }
        });
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        isUiCreated = true;
    }
    @Override
    protected void onDestroy() {
        if (keyboardPopupWindow != null) {
            keyboardPopupWindow.releaseResources();
        }
        super.onDestroy();
    }
}이 코드 는 키보드 팝 업 윈도 라 는 사용자 정의 뷰 를 통 해 키보드 팝 업 및 버튼 클릭 효 과 를 실현 하 는 것 으로 간단 하 다.주의해 야 할 것 은 isUiCreated 라 는 플래그 비트 입 니 다.onWindow FocusChanged 등 을 통 해 현재 페이지 로 딩 이 끝 난 후 사용자 정의 키보드 상 태 를 새로 고 쳐 야 합 니 다.그렇지 않 으 면 오류 가 발생 할 수 있 습 니 다.2.사용자 정의 디지털 키보드 의 코드:
public class KeyboardPopupWindow extends PopupWindow {
    private static final String TAG = "KeyboardPopupWindow";
    private Context context;
    private View anchorView;
    private View parentView;
    private EditText editText;
    private boolean isRandomSort = false;//        
    private List<Integer> list = new ArrayList<>();
    private int[] commonButtonIds = new int[]{R.id.button00, R.id.button01, R.id.button02, R.id.button03,
            R.id.button04, R.id.button05, R.id.button06, R.id.button07, R.id.button08, R.id.button09};
    /**
     * @param context
     * @param anchorView
     * @param editText
     * @param isRandomSort         
     */
    public KeyboardPopupWindow(Context context, View anchorView, EditText editText, boolean isRandomSort) {
        this.context = context;
        this.anchorView = anchorView;
        this.editText = editText;
        this.isRandomSort = isRandomSort;
        if (context == null || anchorView == null) {
            return;
        }
        initConfig();
        initView();
    }
    private void initConfig() {
        setOutsideTouchable(false);
        setFocusable(false);
        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        forbidDefaultSoftKeyboard();
    }
    /**
     *             
     */
    private void forbidDefaultSoftKeyboard() {
        if (editText == null) {
            return;
        }
        if (android.os.Build.VERSION.SDK_INT > 10) {//4.0  ,                   
            try {
                Class<EditText> cls = EditText.class;
                Method setShowSoftInputOnFocus;
                setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setShowSoftInputOnFocus.setAccessible(true);
                setShowSoftInputOnFocus.invoke(editText, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *       popupwindow  outside     :        ,       view
     *
     * @param isTouchable
     */
    public void refreshKeyboardOutSideTouchable(boolean isTouchable) {
        setOutsideTouchable(isTouchable);
        if (!isTouchable) {
            show();
        } else {
            dismiss();
        }
    }
    private void initView() {
        parentView = LayoutInflater.from(context).inflate(R.layout.keyboadview, null);
        initKeyboardView(parentView);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(parentView);
    }
    private void initKeyboardView(View view) {
        LinearLayout dropdownLl = view.findViewById(R.id.dropdownLl);
        dropdownLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        //①          
        for (int i = 0; i < commonButtonIds.length; i++) {
            final Button button = view.findViewById(commonButtonIds[i]);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int curSelection = editText.getSelectionStart();
                    int length = editText.getText().toString().length();
                    if (curSelection < length) {
                        String content = editText.getText().toString();
                        editText.setText(content.substring(0, curSelection) + button.getText() + content.subSequence(curSelection, length));
                        editText.setSelection(curSelection + 1);
                    } else {
                        editText.setText(editText.getText().toString() + button.getText());
                        editText.setSelection(editText.getText().toString().length());
                    }
                }
            });
        }
        //②            
        view.findViewById(R.id.buttonDot).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int curSelection = editText.getSelectionStart();
                int length = editText.getText().toString().length();
                if (curSelection < length) {
                    String content = editText.getText().toString();
                    editText.setText(content.substring(0, curSelection) + "." + content.subSequence(curSelection, length));
                    editText.setSelection(curSelection + 1);
                } else {
                    editText.setText(editText.getText().toString() + ".");
                    editText.setSelection(editText.getText().toString().length());
                }
            }
        });
        //③          
        view.findViewById(R.id.buttonCross).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int length = editText.getText().toString().length();
                int curSelection = editText.getSelectionStart();
                if (length > 0 && curSelection > 0 && curSelection <= length) {
                    String content = editText.getText().toString();
                    editText.setText(content.substring(0, curSelection - 1) + content.subSequence(curSelection, length));
                    editText.setSelection(curSelection - 1);
                }
            }
        });
    }
    public void show() {
        if (!isShowing() && anchorView != null) {
            doRandomSortOp();
            this.showAtLocation(anchorView, Gravity.BOTTOM, 0, 0);
        }
    }
    /**
     *       
     */
    private void doRandomSortOp() {
        if (parentView == null) {
            return;
        }
        if (!isRandomSort) {
            for (int i = 0; i < commonButtonIds.length; i++) {
                final Button button = parentView.findViewById(commonButtonIds[i]);
                button.setText("" + i);
            }
        } else {
            list.clear();
            Random ran = new Random();
            while (list.size() < commonButtonIds.length) {
                int n = ran.nextInt(commonButtonIds.length);
                if (!list.contains(n))
                    list.add(n);
            }
            for (int i = 0; i < commonButtonIds.length; i++) {
                final Button button = parentView.findViewById(commonButtonIds[i]);
                button.setText("" + list.get(i));
            }
        }
    }
    public void releaseResources() {
        this.dismiss();
        context = null;
        anchorView = null;
        if (list != null) {
            list.clear();
            list = null;
        }
    }  
}코드 구현 의 논 리 는 상대 적 으로 간단 합 니 다:4.567917.popupwindow 에 contentView,팝 업 위치,경계 외 터치 파라미터 등 수 치 를 설정 하여 전체적인 스타일 의 효 과 를 실현 합 니 다
물론 이 같은 방식 외 에 도 시스템 의 KeyboardView 와 Keyboard 를 이용 해 효 과 를 낼 수 있다.
모방 하 는 과정 에서 이 효 과 를 실현 하 는 것 은 체험 적 인 세부 사항 과 관련 될 수 있 고 위 챗 은 바로 이 점 을 해 냈 기 때문에 사용 차원 에서 편리 할 것 이다.어떤 세부 적 인 점 은 전체적인 효 과 를 실현 하 는 것 보다 더 번 거 로 울 수 있 지만 가끔 은 무시 하기 쉬 운 구구단 이 남 다른 점 이다.
원본 주소:
https://github.com/ganshenml/KeyboardPopupWindow
여기까지 면 끝 이 야.
이상 은 안 드 로 이 드 가 위 챗 디지털 키 보드 를 모방 한 상세 한 내용 입 니 다.더 많은 안 드 로 이 드 디지털 키보드 에 관 한 자 료 는 우리 의 다른 관련 글 을 주목 하 세 요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.