我想制作一个更新其内容并定期显示在窗口顶部的 View 。我找到了一个在窗口顶部创建 View 的示例( http://blog.daum.net/mailss/18 )。该 Activity 创建一个 UI,如果我触摸启动服务按钮, View 将显示其文本。但是当 View 创建后,它不会更新其内容。我尝试添加简单的代码来计算 View 更新的次数,但它不起作用。如何定期更改 View 的内容?我应该在服务中添加循环代码吗?我需要您的建议,谢谢。
1.AlwaysOnTopActivity.java
public class AlwaysOnTopActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this); //start button
findViewById(R.id.end).setOnClickListener(this); //stop button
}
@Override
public void onClick(View v) {
int view = v.getId();
if(view == R.id.start)
startService(new Intent(this, AlwaysOnTopService.class));
else
stopService(new Intent(this, AlwaysOnTopService.class));
}
}
2.AlwaysOnTopService.java
public class AlwaysOnTopService extends Service {
private TextView tv;
@Override
public IBinder onBind(Intent arg0) { return null; }
@Override
public void onCreate() {
super.onCreate();
tv = new TextView(this); //creating view
tv.setText("This view is always on top.");
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tv.setTextColor(Color.BLUE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, //to always on top
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,//for touch event
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(tv, params);//We must configure the permission in the manifest
}
@Override
public void onDestroy() {
super.onDestroy();
if(tv != null) //terminating the view
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(tv);
tv = null;
}
}
}
最佳答案
按照描述使用 LocalBroadcastManager
here 。在 onReceive
方法中更新您的 UI
关于java - 更新始终位于顶部的 Android View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24504759/