1

我不知道为什么我不能生成自定义密码。

public void GeneratePass(View view) {

    EditText TextField = (EditText)findViewById(R.id.DigitsField);
    int DigitsNum = Integer.parseInt(TextField.getText().toString());
    if (DigitsNum != 1){
        Random Pass = new Random();
        int num1 = Pass.nextInt(10);
        TextView PassText = (TextView) findViewById(R.id.PassText);
        PassText.setText(num1);
    }
}

我创建了这个文本字段(EditText),你可以在其中写下你想要密码的位数,我试着把

    EditText TextField = (EditText)findViewById(R.id.DigitsField);
    String Digits = TextField.getText().toString();
    int DigitsNum = Integer.parseInt(Num);

并更改 if(DigitsNum == 1)... 但是当我写数字时(我只是为 1 编码)我尝试写 1 但它只是崩溃或停止工作。

4

1 回答 1

0

尝试这样的事情并根据您的需要进行修改:

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>
于 2015-08-17T00:24:10.100 回答