可藉由 HideReturnsTransformationMethod 物件來轉換明碼 以及 PasswordTransformationMethod 物件來轉換成暗碼
建立物件後再呼叫 EditText 的 setTransformationMethod(), 傳入剛剛產生的物件即可完成轉換
Source Code
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; public class MainActivity extends ActionBarActivity { private EditText mInputPassword; private CheckBox mShowPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initLayoutComponents(); } private void initLayoutComponents() { mInputPassword = (EditText) findViewById(R.id.password); mShowPassword = (CheckBox) findViewById(R.id.switchPassword); mShowPassword.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mInputPassword.setTransformationMethod(new HideReturnsTransformationMethod()); } else { mInputPassword.setTransformationMethod(new PasswordTransformationMethod()); } } }); } }
第33行及35行即為轉換的過程
R.layout.activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.changepasswordtostar.MainActivity" > <EditText android:id="@+id/password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/input_password_hint" android:inputType="textPassword"/> <CheckBox android:id="@+id/switchPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/password" android:layout_alignLeft="@+id/password" android:text="@string/showPasswrod"/> </RelativeLayout>