无法解析符号'post'

时间:2018-03-11 20:09:19

标签: android handler runnable

以下代码显示即使使用import android.os.Handler;也无法解析符号发布的错误。并且无效的方法声明,Runnable对象需要返回类型。

TextView tv = (TextView) this.findViewById(R.id.txt);

String[] str = new String[] { "72", "71", "70",
        "73", "75", "74", "69", "76", "77", "78" };

final Handler h = new Handler();

h.post(new Runnable() {
    @Override
    public void run() {
        Random generator = new Random();
        final int random = generator.nextInt(str.length);
        tv.setText(str[random]);
        h.postDelayed(this, 1000);
    }
});

2 个答案:

答案 0 :(得分:0)

导入是正确的,问题似乎在runnable中。如果你想延迟运行rask,直接方法就是postDelay。两个论点,一个可运行的和延迟。

h.postDelay(new Runnable ...,1000);

答案 1 :(得分:0)

这是因为您在类中的方法之外调用方法post()

例如,如果你的代码在Activity类中,

这是错误的:

public class MainActivity extends AppCompatActivity {

    final Handler h = new Handler();
    // This is outside a method. It's wrong.
    h.post(new Runnable() {
        @Override
        public void run() {
            Random generator = new Random();
            final int random = generator.nextInt(str.length);
            tv.setText(str[random]);
            h.postDelayed(this, 1000);
        }
    });

    ...

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
    }
}

这是对的:

public class MainActivity extends AppCompatActivity {

    private void generateRandom() {
      final Handler h = new Handler();
       h.post(new Runnable() {
        @Override
        public void run() {
            Random generator = new Random();
            final int random = generator.nextInt(str.length);
            tv.setText(str[random]);
            h.postDelayed(this, 1000);
        }
      });
    }

    ...

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
    }
}