我是android生态系统的新手。我想知道有什么方法可以在最终用户的应用程序活动布局更改时收到通知。如果问题是重复,我很抱歉,我搜索了我认为相关的关键字并找不到答案。 (注意:我不想从后台线程更改UI,我只是希望在布局根据用户使用应用程序更改时收到通知)
答案 0 :(得分:1)
您可以创建一个自定义布局,并基本上覆盖它的onDraw方法,该方法将在刷新/更新布局时调用,然后从那里获得通知。
<强>样品:强>
假设您使用LinearLayout
建立父级布局。
public class Sample2 extends LinearLayout {
public Sample2(Context context) {
super(context);
}
public Sample2(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Sample2(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Log.d("UPDATE", "I am REFRESHED"); //will print if this layout is refresh,updated, or invalidated.
super.onDraw(canvas);
}
}
在xml中使用它:
<?xml version="1.0" encoding="utf-8"?>
<com.example.sfdsffsdf.Sample2 xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</com.example.sfdsffsdf.Sample2>
答案 1 :(得分:1)
您可以在布局上设置OnGlobalLayoutListener,并在该布局或其任何子项的状态或可见性发生变化时收到通知:
myLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Do something
}
};