无法解析方法 'getWindow()'

问题描述:

在下面的代码行的getWindow()方法无法解析方法 'getWindow()'

this.getWindow()setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)。

导致以下错误

无法解析方法 'getWindow()'

的代码的故障线路是在该方法中

private void setButtonListener(Button button){ 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      String textString = editText.getText().toString(); 
      textView.setText(textString); 
      editText.getText().clear(); 


      InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(textView.getWindowToken(), 0); 

      this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
     } 
    }); 
} 

的底部当键盘关闭时,我想让我的editText失去焦点。

我在活动班,所以我不确定问题出在哪里。 this有一个getWindow()方法吗?

+0

里面的onClick,这指的是OnClickListener。您需要使用MyTopLevelClassName.this。 –

你可以关闭这样

private void setButtonListener(Button button){ 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      String textString = editText.getText().toString(); 
      textView.setText(textString); 
      editText.getText().clear(); 


      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0); 

     } 
    }); 
} 

软键盘如果你想切换

InputMethodManager im =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
im.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); 

您可以使用OnFocusChangeListener隐藏软键盘,失去专注

EditText editText = (EditText) findViewById(R.id.textbox); 
OnFocusChangeListener ofcListener = new MyFocusChangeListener(); 
editText.setOnFocusChangeListener(ofcListener); 


private class MyFocusChangeListener implements OnFocusChangeListener { 

    public void onFocusChange(View v, boolean hasFocus){ 

     if(v.getId() == R.id.textbox && !hasFocus) { 

      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 

     } 
    } 
} 

找到解决方案

在活动:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

在片段:

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

尝试这种解决方案 - >只需加提前名。

MainActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 

代替this.getWindow()使用YourActivity.this.getWindow()

试试这个:

YourActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);