从Android中的数组中获取随机字符串并将其放置在文本视图中

Iva*_*res 0 android

我有作为一个小项目来创建的阵列NameSurname并且Email其中我在使用值创建的xml

这是我的 xml Name,以字符串命名names

<resources>
    <string name="names">
        <item>Ivan</item>
        <item>Santiago</item>                    
        .....
    </string>
</resources>
Run Code Online (Sandbox Code Playgroud)

这是我的 XML,名为 Surnames,带有一个名为 surnames 的字符串

<resources>
    <string name="surnames">
        <item>Rodríguez</item>
        <item>Gómez</item>
        <item>López</item>
        .....
    </string>
</resources>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

public class Registro extends AppCompatActivity implements View.OnClickListener {

    private TextView Nombre,Apellido,Correo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registro);
        //Seteamos las Cajas de Texto
        Nombre = (TextView) findViewById(R.id.txtNombre);
        Apellido = (TextView) findViewById(R.id.txtApellido);
        Correo = (TextView) findViewById(R.id.txtCorreo);
        //Ponemos en Modo de Escucha al Boton
        findViewById(R.id.btnGenerar).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

    }
}
Run Code Online (Sandbox Code Playgroud)

我想从 XML 数组中随机选择名称并将它们显示在文本视图中。

nsc*_*012 5

把你的名字放在一个字符串数组中:

<resources>
    <string-array name="nomes">
        <item>Ivan</item>
        ...
    </string-array>
    ...
</resources>
Run Code Online (Sandbox Code Playgroud)

然后使用Random从数组中获取一个随机名称:

private String[] names;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    names = getResources().getStringArray(R.array.nomes);
}

@Override
public void onClick(View v) {
    int randomIndex = new Random().nextInt(names.length);
    String randomName = names[randomIndex];
    yourTextView.setText(randomName);
}
Run Code Online (Sandbox Code Playgroud)