在android中使用用户输入创建对象

时间:2018-12-31 18:30:04

标签: java android

我在android中拥有此类,我已将其连接到xml布局,以获取用户输入的名称,年龄,身高和体重。

public class Person {

String name;
int age;
int height;
int weight;

}

我希望用户创建一个新人。我尝试获取用户输入以创建对象,但是如果我编写此代码,则会出错。

 Person editText.getText().toString() = new Person();

允许用户创建新人物的正确方法是什么?

3 个答案:

答案 0 :(得分:1)

使用参数化的构造函数,并在初始化期间将其传递给对象

 public class Person {

                 public Person(String name, int age, int height, int weight) {
                                   this.name = name; 
                                    this.age = age; 
                                    this.height = height;  
                                   ....
                 }



    String name;
    int age;
    int height;
    int weight;

    }

Person person = new Person(editText.getText()。toString(),...);

答案 1 :(得分:0)

因此,首先,Person editText.getText().toString() = new Person();是无效的语法。

您可以执行String myPersonString = editText.getText().toString();。它将创建名为myPersonString的类型为String的局部变量。由于Person类具有多个属性,因此一个人只有一个EditText字段就没有多大意义,因此您可能必须具有多个EditText字段。

private EditText nameText, ageText, heightText, weightText;
// initialize these in your onCreate() like you're already doing with editText

现在我们已经设置好了,就可以获取它们的值。

String name = nameText.getText().toString();
try{
    int age = Integer.parseInt(ageText.getText().toString());
    int height = Integer.parseInt(heightText.getText().toString());
    int weight = Integer.parseInt(weightText.getText().toString());
    Person person = new Person(name, age, height, weight);
} catch(NumberFormatException e){
    e.printStackTrace();
    // AND Do something here to tell your user that their input is invalid!
    // don't just ignore it!
}

当前,您的person类没有构造函数,因此new Person(name, age, height, weight);会给您一个错误,您可以像这样创建类:

class Person{
    private final String name;
    private final int age, height, weight;
    public Person(String name, int age, int height, int weight){
        this.name = name;
        this.age = age;
        this.height = height;
        this.weight = weight;
    }
}

要注意的一件事是使用final。这不是必需的,并且是您现在不需要了解的概念,但是随着您的编程知识的增长,它非常有用。基本上,如果某些事情是最终的,则它的值只能初始化一次,此后不能再更改。

根据您想对Person类执行的操作,您可能不希望它是最终的。还请注意private的使用。在Java中,这是一个好习惯,在您的情况下,要使字段真正有用,您将必须使用getter和setter。或者(不建议)设置字段public或使其不带修饰符,以便同一包中的任何类都可以查看并根据需要对其进行修改。

答案 2 :(得分:0)

人员editText.getText()。toString()=新的Person();

在此行代码中,动态创建对象的引用,但不将值从edittext存储到对象中。

有很多方法可以使用

来存储对象
  1. Setter和getter注入

    Person person = new Person();     person.setAge(AgeeditText.getText()。toString());     person.setHeight(heighteditText.getText()。toString());     person.setName(NameeditText.getText()。toString());     person.setWeight(WeighteditText.getText()。toString());

  2. 构造函数注入

    Person person = new Person(NameeditText.getText()。toString(),AgeeditText.getText()。toString(),...);

.... etc

快乐编码