我在同一个活动上有一个VideoView和一个TextView。这是布局的xml。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rellayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:padding="5dp" />
<TextView
android:id="@+id/numberTicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/purple"
android:textStyle="bold"
android:gravity="top|right"
android:textSize="35dp"
android:maxEms="3"/>
</RelativeLayout>
视频开始播放后,我希望在numberTicker文本视图中显示一个数字。请注意,数字每秒可能会改变4次。无论如何,我遇到的主要问题是确定视频已开始播放并继续更新TextView。
我的尝试:
vid = (VideoView) findViewById(R.id.videoview);
ratings = (TextView) findViewById(R.id.ratingTicker);
vid.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
vid.start();
vid.postDelayed(onEveryQuarterSecond,250);
}
});
...
...
private Runnable onEveryQuarterSecond = new Runnable() {
Random r = new Random();
int uVal, aVal;
@Override
public void run() {
ratings.setText(Integer.toString(r.nextInt()));
}
};
代码Runnable只运行一次,永远不会更新。 我错过了什么吗?
感谢您的帮助!
答案 0 :(得分:1)
您在MediaPlayer
中获得了onPrepared()
个对象。你可以这样使用:
vid.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
this.mediaPlayer = mp; //have mediaPlayer be a class variable
vid.start();
vid.postDelayed(onEveryQuarterSecond,250);
}
});
private Runnable onEveryQuarterSecond = new Runnable() {
Random r = new Random();
int uVal, aVal;
@Override
public void run() {
while(mediaPlayer.isPlaying()) {
ratings.setText(Integer.toString(r.nextInt()));
Thread.sleep(250);
}
}
};
答案 1 :(得分:0)
考虑使用新的Thread来阻止主UI线程:
public void updateEverySecond() {
new Thread(new Runnable() {
@Override
public void run() {
while (mediaPlayer.isPlaying()) {
try {
ratings.setText(Integer.toString(r.nextInt()));
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}