从另一个类访问 TextView
我的主启动类正在加载 main.xml,但我试图弄清楚如何从另一个正在从数据库加载信息的类访问 TextView。我想将该信息发布到 TextView。
到目前为止,我还没有在谷歌上找到任何有用的例子。
编辑: 这是我的类正在执行数据库工作:
import android.widget.TextView;import android.view.View;
public class DBWork{
private View view;
...
TextView tv = (TextView) view.findViewById(R.id.TextView01);
tv.setText("TEXT ME")
但是,每次我这样做时都会遇到空指针异常
I've got my main startup class loading main.xml but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
So far I've not found any helpful examples on Google.
EDIT:
This is my class that is doing the Database work:
import android.widget.TextView;import android.view.View;
public class DBWork{
private View view;
...
TextView tv = (TextView) view.findViewById(R.id.TextView01);
tv.setText("TEXT ME")
Yet, everytime I do that I get a nullpointerexception
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您应该使用 LayoutInflater :
You should use LayoutInflater :
如果我是您,我会将所有 UI 更新保留在您的主
Activity
类中。您只需让DBWork
类返回您想要显示到Activity
的文本。因此,类似于:然后您的数据库类:
请注意,您在
onCreate
期间执行的任何数据库操作都应该尽可能快,因为它们在 UI 线程中运行。如果您要执行长时间运行的数据库查询,那么您应该使用AsyncTask
或创建一个新的Thread
并使用Handler
来更新 UI 。If I were you I'd keep all your UI updates within your main
Activity
class. You just get yourDBWork
class to return the text you want displayed to yourActivity
. So something like:Then your db class:
Please note that any database operations you perform during
onCreate
should be as quick as possible as they are running in the UI thread. If you are going to perform long running database queries then you should use anAsyncTask
or create a newThread
and use aHandler
to update the UI.创建类实例后,您可以将引用传递给所有控件。我个人将所有控件都作为公共变量传递给整个类。
You can pass the references to all your controls after you created your class instance. I personally pass the whole class that has all controls as public variables.
您必须使用 xml 定义 TextView 并为其指定一个 id。示例:
那么您可以使用以下方式在每个类中访问它
You havew to define your TextView using xml and giving it an id. Example:
Then you cann access it in every class using
是的:
但在您必须指定要使用的文件之前:
如果没有,findViewById(R.id.myTextViewInXml); 总是会返回
null
。这是一个例子:
It's right:
But before you have to specify what file you want use by:
Without that the
findViewById(R.id.myTextViewInXml);
alway will returnnull
.This is an example:
在上面的示例中,视图 bt1 来自另一个类。您可以使用类实例访问 bt1 并获取 id。现在,对 bt1 实例执行您想要执行的操作。
注意:确保 bt1 在另一个类中是公开的
In the above example where view bt1 is from another class.you can access bt1 by using class instance and get the id.Now,do what ever you want do with bt1 instance.
Note: Make Sure bt1 is public in another class