简体   繁体   English

如何从另一个 XML 文件中获取 EditText 的文本?

[英]How can i get the text of an EditText from another XML file?

I have a activity which has an AlertDialog which calls a xml file where the EditText is, and I want to get that text and use it to create an object with it.我有一个活动,它有一个 AlertDialog,它调用 EditText 所在的 xml 文件,我想获取该文本并使用它来创建一个对象。

//This code is in Activity2.java/activity2_activity.xml
private Player addPlayer() {
//R.id.txtName and R.id.txtAge are the EditText from another xml file called inputplayer.xml
        txtName =(EditText) findViewById(R.id.txtName);
        txtAge= (EditText)findViewById(R.id.txtAge);

        String name= txtName.getText().toString();
        int age = Integer.valueOf(txtAge.getText().toString());
        
        if (name.length()>20){
            return null;
        }
        if (age < 3 || age > 99){
            return null;
        }
        return new Player(name,age);
    }

Problem is I got an exception when trying to get the Text from both EditText and cant find any solutions.问题是我在尝试从 EditText 获取文本时遇到异常,但找不到任何解决方案。 Exception:例外:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at com.example.juego3enraya.Activity2.addPlayer(Activity2.java:111)引起:java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at com.example.juego3enraya.Activity2.addPlayer(Activity2.java: 111)

You don't get values in xml files.您不会在 xml 文件中获得值。 You get them in Java files.您可以在 Java 文件中获取它们。 Confusing activities and the java code that runs them with xml files is only going to lead you to be very confused.混淆活动和使用 xml 文件运行它们的 Java 代码只会让您感到非常困惑。

You can't search for a view in the root layout if its in the dialog box.如果在对话框中,则无法在根布局中搜索视图。 What you should do is when the dialog window is closed, use dialog.findViewById(R.id.txtAge).getText() to get the value of the edit text when it is closed, and save the value in a variable.您应该做的是在对话框窗口关闭时,使用 dialog.findViewById(R.id.txtAge).getText() 获取关闭时编辑文本的值,并将该值保存在变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM