从另一个类访问TextView

时间:2011-01-05 19:49:50

标签: android view textview

我的主要启动类加载了main.xml,但我正在试图弄清楚如何从另一个从数据库加载信息的类访问TextView。我想将该信息发布到TextView。

到目前为止,我还没有在Google上找到任何有用的示例。

编辑: 这是我正在做数据库工作的课程:

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")

然而,每次我这样做,我都会得到一个nullpointerexception

6 个答案:

答案 0 :(得分:3)

你应该使用LayoutInflater:

        LayoutInflater inflater = getLayoutInflater();
        View myView = inflater.inflate(R.layout.main, null);
        TextView myTextView = (TextView) findViewById(R.id.myTextViewInXml);

答案 1 :(得分:2)

如果我是你,我会在您的主要Activity课程中保留所有UI更新。您只需让DBWork课程将要显示的文字返回到Activity。如下所示:

public class Main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) view.findViewById(R.id.TextView01);
        DBWork db = new DBWork("192.168.2.14:8080/DH/DPost";, "test_db");
        tv.setText(db.getText()); 
    }
}

然后你的db类:

public class DBWork{
    ...
    public String getText(){
        //do stuff
        return "";
    }
}

请注意,您在onCreate期间执行的任何数据库操作都应尽可能快,因为它们在UI线程中运行。如果要执行长时间运行的数据库查询,则应使用AsyncTask或创建新的Thread并使用Handler更新UI。

答案 2 :(得分:1)

您可以在创建类实例后将引用传递给所有控件。我亲自将具有所有控件的整个类作为公共变量传递。

答案 3 :(得分:0)

您必须使用xml定义TextView并为其指定ID。例如:

<TextView android:layout_width="wrap_content"
                  android:layout_height="match_parent"
                  android:textColor="#FFF"
                  android:gravity="center_vertical|right"
                  android:paddingLeft="5dip"
                  android:paddingRight="5dip"
                  android:text="@string/name"
                  android:id="@+id/myTextViewInXml"/>

然后您可以使用

在每个班级中访问它
 TextView myTextView = (TextView) findViewById(R.id.myTextViewInXml);

答案 4 :(得分:0)

没错:

 LayoutInflater inflater = getLayoutInflater();
 View myView = inflater.inflate(R.layout.main, null);
 TextView myTextView = (TextView) findViewById(R.id.myTextViewInXml);

但在您必须指定要使用的文件之前:

  

setContentView(包含R.id.myTextViewInXml的XML文件的id)

如果不这样,findViewById(R.id.myTextViewInXml);总会返回null

这是一个例子:

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.virtualtour); // before !!
        progress_bar = (ProgressBar) findViewById(R.id.vt_progress);
        loading_ly = (RelativeLayout) findViewById(R.id.vt_layout_loading);
        panorama_description = (TextView) findViewById(R.id.vt_description);
        virtualtour_relatively = (RelativeLayout) findViewById(R.id.vt_layout_opengl);

.........

答案 5 :(得分:0)

TextView bt1 =m_activity.findViewById(R.id.textview1);

在上面的示例中,视图bt1来自另一个类。您可以使用类实例访问bt1并获取id.Now,执行您想要的bt1实例。

注意:确保bt1在另一个类中是公开的