使用在另一个类中调用的方法设置edittext文本



我在活动中初始化了edittext,如:

EditText date;
DateDialog date_class;
protected void onCreate(Bundle savedInstanceState) {
date = findViewById(R.id.date_input);
date.setOnClickListener(this);
date_class = new DateDialog();
........
}

以及onclicklistner:

public void onClick(View v) {
.....
date_class.SetDateString();
.....
}

另一个类(DateDialog(中的SetDateString((方法是:

public void SetDateString() {
String name = "bla bla bla";
Activity act= new Activity();//defining the activity object
act.setdate(name);//sends the string to the activity's method where it will set a text for the edittext
}

因此,它发送一个带有act.setdate(name(方法的字符串,该方法在活动中定义为:

public void setdate(String name){
date.setText(name);// sets a text for the edittext
}

我已经为您简化了代码来解释这一点,我正在使用其他类来完成此活动,但不幸的是,它返回了以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

这种方法与标准数据流相反,即使你让它工作起来,它也可能导致线程问题。您不应该试图从除UI本身之外的任何类操作UI。

如果我推断正确,你想点击一个文本框,打开一个对话框,在对话框中做一些事情,然后更新你的初始活动吗?在这种情况下,您需要使用接口。

在活动的底部定义一个接口,现在在封闭类之外。

interface DialogCallback{
String doSomething(String name);
}

在DateDialog类中添加一个变量

private DialogCallback dialogCallback;  

在你的主要活动中,将此添加到你的类初始化中:

implements DialogCallback  

执行ALT+Enter并实现方法doSomething(字符串名称(。初始化DateDialog类时,需要设置回调变量,可以在init调用中进行,也可以在DateDialog类别中作为单独的setter进行。

void setCallback(DialogCallback callback){
this.dialogCallback = callback;
}

然后在初始化类之后设置它:

date_class = new DateDialog();
date_class.setCallback(this);

最后,从更改您的功能

public void SetDateString() {
String name = "bla bla bla";
Activity act= new Activity();//defining the activity object
act.setdate(name);//sends the string to the activity's method where it will  set a text for the edittext
}

public void setDateString(){
String name = "foo";
dialogCallback.doStuff(name);
}

现在它将把这个字符串传回到你的主类;DoStuff(字符串名称(";函数,然后使用它来更新UI
此外,您的变量应该像"dateClass";而不是";date_ class";函数不应以大写字母开头
至于为什么代码不起作用,我的猜测是Activity=new Activity((。这毫无意义,你没有创建任何特定类的实例,即使你创建了,它也会是";新的";这意味着任何先前定义的ui元素都是不可访问的。

最新更新