0
public class MainActivity extends Activity {

   TextView textview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
    setContentView(R.layout.activity_main);

      textview = (TextView)findViewById(R.id.textView6);
      //other method,startservice()and so on.

      //and there is BroadcastReceiver to receive a flag from service.
      public static class Receiver extends BroadcastReceiver{

      @Override
          public void onReceive(Context context, Intent intents) {
          intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          textview.setText("set");

这是我的代码。我想要的只是 textview.setText() onReceive。

我的第一次尝试,textview 是静态的。但是静态变量似乎在另一个方法运行期间被杀死。textview 设置为空,不能设置文本。

所以我尝试让 textview 不是静态的。但还有第二个问题。当我这样做时,我必须获取 new MainActivity() 才能访问 textview。这没有很好地工作。复杂。

我如何从静态方法中获取文本视图。

4

1 回答 1

0

You cannot access non-static variable/method within static method because the static method exists regardless if there is instance of your class or no

You can maintain a static instance of your MainActivity (initialize it in the constructor or in onCreate) and use it to access the textview

For example

public class MainActivity extends Activity {
    private static MainActivity instance;

    protected void onCreate(Bundle savedInstanceState) {
      instance = this;
    }

  public void onReceive(Context context, Intent intents) {
     instance.textview.setText("set");     
}

I do not know what you are trying to achieve here or when this onReceive will be called, but having static class for BroadcastReceiver does not seem to be good.

Another thing you will need to update the textview from the UI thread which you can do using runOnUiThread

instance.runOnUiThread(new Runnable() {

        public void run() {
            // update your textview             
        }
    });
于 2013-02-09T10:27:04.623 回答