如何从我的班级访问Activity UI?

Mar*_*coS 14 android android-context

我有一个活动,它创建了我的类的对象实例:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

如何在我的类中使用UI对象(不扩展Activity)?我应该将一些上下文传递给我的Points类吗?我该怎么办?

Hou*_*ine 18

看到你的帖子,我已经编辑过,以解决问题

希望它有所帮助:=)

这是编辑:

file MyActivity.java:
    public class MyActivity extends Activity {
    TextView myView ;
    protected void onCreate(android.os.Bundle savedInstanceState) {
        myView = (TextView)findViewById(R.id.myView);
            Points myPoints = new Points(this);
            myPoints.displayMsg("Hello World !!!");
    }  
    }

--------------------------------------------------------------

file Points.java:
private class Points {
    protected MyActivity context;
    //add a constructor with the Context of your activity
    public Points(MyActivity _context){
        context = _context;
    }

    public void displayMsg( final String msg){
        context.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                context.myView.setText(msg);    
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Sipty:我已经编辑了他的问题供他理解,因为我不想复制粘贴答案中的所有代码,然后我在其他人的答案中添加了编辑的部分:D (2认同)