【问题标题】:Sharing data between an activity and a class在活动和班级之间共享数据
【发布时间】:2014-10-12 08:00:34
【问题描述】:

我有一个活动MyActivity,它包含一个服务类MyService。 我希望服务将String 数据发送到活动,然后使用此数据创建button
this 帖子之后,我在活动中创建了一个static 方法。
问题当然是我不能在静态上下文中使用this

public class MyActivity extends Activity {


    private MyService myService;


    public void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.main);
        myService = new MyService();

    }


    public static void connectMethod (String buttonName) {

        Button btn = new Button(this); // error
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);

    }
}





public class MyService {

    ...

    private void showButton (String data) {
        MyActivity.connectedMethod(data);
    }
}

【问题讨论】:

  • 了解android os中的“绑定服务”

标签: android


【解决方案1】:

避免error 的两种可能解决方案:

  1. public static void connectMethod (Context context, String buttonName) {
    
        Button btn = new Button(context); 
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);
    
    }
    
    // ...
    
    public class MyService {
    
        private Context context;
    
        public MyService(Context context) {
            this.context = context;
        }
        ...
    
        private void showButton (String data) {
            MyActivity.connectedMethod(context, data);
        }
     }
    
  2. 或者创建一个静态类字段:private static Context context;

    public static void connectMethod (String buttonName) {
    
        Button btn = new Button(context); 
        btn.setId(i);
        final int buttonID = btn.getId();
        btn.setText(buttonName + buttonID);
    
    }
    

【讨论】:

    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多