尝试这样的事情并根据您的需要进行修改:
Java 代码(在您的 onCreate 方法中添加此代码):
final TextView passText = (TextView) findViewById(R.id.passText);
final EditText digitsField = (EditText) findViewById(R.id.digitsField);
Button generatePassword = (Button) findViewById(R.id.generatePassword);
generatePassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int passwordLength = Integer.parseInt(digitsField.getText().toString());
String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char[] allowedCharsArray = allowedChars.toCharArray();
char[] chars = new char[passwordLength];
Random random = new Random();
for (int i = 0; i < passwordLength; i++) {
chars[i] = allowedCharsArray[random.nextInt(allowedChars.length())];
}
passText.setText(chars, 0, passwordLength);
}
});
XML 布局(使用当前布局进行编辑):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Password"
android:layout_gravity="center"
android:id="@+id/passText" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:id="@+id/digitsField" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate Password"
android:layout_gravity="center"
android:id="@+id/generatePassword" />
</LinearLayout>