密码生成器错误(Android)



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

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,但它只是崩溃或停止工作

尝试这样做,并根据您的需要修改它:

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>

相关内容

  • 没有找到相关文章