postDelayed方法无法识别

时间:2015-05-18 20:39:43

标签: android android-handler

我开始尝试学习MoodScanner应用程序。我收到与Handler对象相关的错误。我已经导入了它但仍然无法识别postDelayed方法并且它正在说

cannot resolve symbol postDelayed

Unexepected token..

以下是代码

package com.example.manju.moodscanner;

import android.graphics.drawable.AnimationDrawable;

import android.support.v7.app.ActionBarActivity;

import android.os.*;

import android.os.Bundle;

import android.os.Handler;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

private TextView result;
private ImageView thumbPrint;
private Runnable mRunnable;
private AnimationDrawable thumbAnimation;
private String[] moodResults;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    moodResults= new String[] {
            "Someone is cranky!",
            "You are my sunshine!",
            "No Comments...",
            "You're stressed out!",
            "Happy camper",
            "Not your day!",
            "Smile- its good for you.",
            "In the clouds...",
            "Pensive",
            "Sad!",
            "Excited!"
    };

    thumbPrint= (ImageView) findViewById(R.id.thumbPrint);
    thumbPrint.setBackgroundResource(R.drawable.thumb_animation);
    thumbAnimation=(AnimationDrawable) thumbPrint.getBackground();

    result= (TextView) findViewById(R.id.resultText);

    thumbPrint.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            showResult();
            //Toast.makeText(getApplicationContext(),"Helloo hru!",Toast.LENGTH_LONG).show();
            return true;
        }
    });
}

public void showResult(){
    mRunnable=new Runnable() {
        @Override
        public void run() {
            int rand= (int) (Math.random()* moodResults.length);
            result.setText(moodResults[rand]);
        }
    };
}
Handler mHandler= new Handler();
mHandler.postDelayed(mRunnable, 5000)
}

2 个答案:

答案 0 :(得分:0)

处理程序需要在showResult()方法中,或者在调用showResult()之后需要调用它,因为mRunnable并不存在。

答案 1 :(得分:0)

尝试使用v

中使用onLongClick参数的每个视图的处理程序
//....
thumbPrint.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        v.postDelayed(new Runnable() {
            @Override
            public void run() {
                int rand= (int) (Math.random()* moodResults.length);
                result.setText(moodResults[rand]);
            }
        }, 5000);
        // also use the context from v, not application
        //Toast.makeText(v.getContext(),"Helloo hru!",Toast.LENGTH_LONG).show();
        return true;
    }
});