How to access Activity UI from my class?

前端 未结 7 1113
情歌与酒
情歌与酒 2020-12-01 14:53

I have an activity which creates an object instance of my class:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (Text         


        
相关标签:
7条回答
  • 2020-12-01 15:29

    Could work using an interface

    file MyActivity.java:

    public class MyActivity extends Activity implements Points.MyListener {
    
        TextView myView;
        ... onCreate(...){
            myView = (TextView)findViewById(R.id.myView);
            Points myPoints  = new Points();
    
            //pass in MyActivity's instance of the listener
            myPoints.addListener(this);
        }
    
        @Override
        public void updateTextView(String message){
            myView.setMessage(message);
        }
    }
    

    file Points.java:

    public class Points {
    
        public Points(){
    
        }
    
        public interface MyListener{
            void updateTextView(String message);
        }
        MyListener myListener;
    
        public void addListener(MyListener listener){
            myListener = listener;
        }
    
        public void updatePoints(){
            //do some operations in calculatePoints()
            String points = calculatePoints();
            //update views using MyActivity's implementation of updateTextView()
            myListener.updateTextView(points);
        }
    
    }
    

    Doing it this way, events can be fired / messages sent, for lack of better terms, from the external class to update the Activity UI. This might be overkill if all sb need is to call a method in the Points class that returns something

    0 讨论(0)
提交回复
热议问题