如果EditText不为空,则隐藏软件键盘



当登录活动加载了已经填充了sharedPreferences数据的EditText时,我试图隐藏软件键盘。

我已经在其他问题中尝试了这段代码,但它不起作用:

if(inputEmail.getText().toString().trim() != null){
    InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
    inputManager.hideSoftInputFromWindow(inputEmail.getWindowToken(),0);
}
你能给我一些建议来解决这个问题吗?编辑:这是我的XML布局:
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dip" >
    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
        <!--  View Title Label -->
        <TextView
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"
            android:text="LOGIN"
            android:textSize="25dip"
            android:textStyle="bold"
            android:textColor="#FFF" />
        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.37"
            android:background="#900099CC"
            android:text="Registrazione"
            android:textColor="#FFF"
            android:textStyle="bold" />
    </LinearLayout>
    <!--  Email Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Email o username" 
        android:textColor="#FFF" />
    <View 
        android:layout_width="fill_parent"
        android:layout_height="1dp"       
        android:background="#FFF" />
    <!--  Email TextField -->
    <EditText
        android:id="@+id/loginEmail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:windowSoftInputMode="stateHidden"
        android:imeOptions="actionNext"
        android:background="#97FFFFFF"
        android:padding="5dp"
        android:layout_marginTop="5dp"/>
    <!--  Password Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Password" 
        android:textColor="#FFF"/>
    <View 
        android:layout_width="fill_parent"
        android:layout_height="1dp"       
        android:background="#FFF" />
    <!--  Password TextField -->
    <EditText
        android:id="@+id/loginPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:background="#97FFFFFF"
        android:padding="5dp"
        android:layout_marginTop="5dp"  />
    <CheckBox
        android:id="@+id/chkPref"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFFFFF"
        android:background="#80FFFFFF"
        android:text="Salva dati di accesso"
        android:checked="true"
        android:padding="5dp" 
        android:layout_marginTop="15dp"/>
    <!--  Login Button -->
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Login"
        android:textColor="#FFF"
        android:background="#97000066" />
    </LinearLayout>
</ScrollView>

我使用InputMethodManager只在这种情况下,当我试图隐藏键盘,请帮助!

谢谢

EDIT-2:活动代码:

public class Login extends Activity 
{
String nomeGiocatore;
Intent intentRegistrazione;
JsonDB jParser = new JsonDB();
Button btnLogin;
Button btnLinkToRegister;
public static EditText inputEmail;
public static EditText inputPassword;
private CheckBox chkPref;
Editor editor;

@Override
public void onCreate(Bundle savedInstanceState) 
{    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    // Elementi della UI
    inputEmail = (EditText) findViewById(R.id.loginEmail);
    inputPassword = (EditText) findViewById(R.id.loginPassword);
    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
    chkPref = (CheckBox) findViewById(R.id.chkPref);
    chkPref.setTextColor(Color.WHITE);
    // utilizzo le sharedpreferences per salvare i dati del login e recuperarli alla successiva apertura dell'app
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 -  private mode
    editor = pref.edit();

    // la tastiera viene nascosta se il campo è già compilato con i dati salvati nelle shared preferences
    if(inputEmail.getText().toString().trim() != "")
    {
        Log.d("KYBRD", "Valor: " + inputEmail.getText().toString().trim());
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
        inputManager.hideSoftInputFromWindow(inputPassword.getWindowToken(),0);
    }

    inputPassword.setText(pref.getString("password", ""));
    // Salvo il nome del giocatore preso dall'intent registrazione (se si è passati per tale schermata)
    intentRegistrazione = getIntent();
    String username = intentRegistrazione.getStringExtra("nomeGiocatore");
    if(username != null)
    {
        inputEmail.setText(username);
        inputPassword.setText("");
        editor.clear();
        editor.commit();
    }
    else
        inputEmail.setText(pref.getString("name", ""));
    // Override del bottone, in modo che funzioni da "tasto Invio"
    inputPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() 
    {   
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || 
                    event.getAction() == KeyEvent.ACTION_DOWN &&
                    event.getKeyCode() == KeyEvent.KEYCODE_ENTER) 
            {
                new CheckUser(Login.this,inputEmail.getText().toString().trim(),inputPassword.getText().toString().trim()).execute();
            }
            if (chkPref.isChecked())
            {
                editor.putString("name", inputEmail.getText().toString().trim());
                editor.putString("password", inputPassword.getText().toString().trim());
                editor.commit();
            }
            else
            {
                editor.clear();
                editor.commit();
            }
            return true;
        }
    });
    inputPassword.setImeActionLabel("Invia", KeyEvent.KEYCODE_ENTER);
    // Override del metodo onClick per controllare la presenza della connessione, 
    btnLogin.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v) 
        {   
            // controllo se esiste una connessione
            ConnectivityManager manager = (ConnectivityManager)getSystemService(Login.CONNECTIVITY_SERVICE);
            Boolean isWifiConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
            Boolean isMobileConnected = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
            if(!isWifiConnected && !isMobileConnected)
            {
                new AlertDialog.Builder(Login.this)
                .setTitle("Connessione non attiva!")
                .setMessage("Per giocare a ProjectM è necessaria la connessione alla rete. Vuoi andare alla pagina delle impostazioni?")
                .setNegativeButton("Attiva Wifi", new DialogInterface.OnClickListener() 
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() 
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setNeutralButton("Attiva rete mobile", new DialogInterface.OnClickListener() 
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which) 
                    {
                        startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
                        dialog.dismiss();
                    }
                }).create().show();
            }
            else
            {
                // Verifico correttezza dati login
                new CheckUser(Login.this,inputEmail.getText().toString().trim(),inputPassword.getText().toString().trim()).execute();
                if (chkPref.isChecked())
                {
                    editor.putString("name", inputEmail.getText().toString().trim());
                    editor.putString("password", inputPassword.getText().toString().trim());
                    editor.commit();
                }
                else
                {
                    editor.clear();
                    editor.commit();
                }
            }
        }
    });
    // Override del metodo onClick che porta alla schermata di registrazione
    btnLinkToRegister.setOnClickListener(new View.OnClickListener() 
    { 
        @Override
        public void onClick(View view) 
        {
            Intent intentToRegistration = new Intent(getApplicationContext(),Register.class);
            startActivity(intentToRegistration);
            finish();
        }
    }); 
}
}
下面是代码,希望对你有所帮助!

您应该将隐藏键盘代码替换为以下行:

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

现在有帮助了。

欢呼

隐藏软键盘尝试使用:

/**
     * Hides Soft Keyboard displayed by currently focused EditText
     * 
     * @param pEditText EditText currenly focused EditText
     */
    protected void hideSoftKeyboard( EditText pEditText )
    {
        InputMethodManager lInputMethodManager = (InputMethodManager) pEditText.getContext().getSystemService( Context.INPUT_METHOD_SERVICE );
        lInputMethodManager.hideSoftInputFromWindow( pEditText.getWindowToken() , 0 );
    }

检查trim()的result是否为空字符串,而不是null

使用android:windowSoftInputMode="stateHidden"来隐藏键盘

相关内容

  • 没有找到相关文章

最新更新