我正在文档中查找某种事件,该事件允许我检测何时创建视图或何时将视图附加到活动,在视图层次结构中的任何位置,无论是一层深还是多层深.
像这样的方法是理想的,无论是在 Activity 级别、Window 级别还是 Window.DecorView 级别:
void ViewAttachedToActivity(View view)
{
... //triggered each time an individual view is added to activity
}
重要的部分是我希望能够从 Activity 的上下文中检测到这个事件,而不是从子视图本身的上下文中。
下面是我正在尝试完成的粗略演示。我想知道是否存在更有效的方法:
PS我知道我可以通过子类化所有文本控件(如TextView、EditText、Button等)来完成自定义字体部分,并使用它们而不是库存控件,但我正在寻找一种简单的解决方法来帮助我避免这种情况.
(请原谅这段代码是用 C# 编写的,使用 Mono for Android,它应该很容易理解并在心理上转换为 Java)
public class BaseActivity : SherlockFragmentActivity
{
public Typeface Voltaire { get; set; }
bool pendingLayout = false;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Voltaire = Typeface.CreateFromAsset(Assets, "fonts/voltaire-regular.ttf");
Window.DecorView.ViewTreeObserver.GlobalLayout += new EventHandler(ViewTreeObserver_GlobalLayout);
Window.DecorView.ViewTreeObserver.PreDraw += new EventHandler<ViewTreeObserver.PreDrawEventArgs>(ViewTreeObserver_PreDraw);
}
void ViewTreeObserver_GlobalLayout(object sender, EventArgs e)
{
pendingLayout = true;
}
void ViewTreeObserver_PreDraw(object sender, ViewTreeObserver.PreDrawEventArgs e)
{
if (pendingLayout)
{
pendingLayout = false;
SetTypeFace(Window.DecorView, Voltaire);
}
}
public void SetTypeFace(View view, Typeface typeface)
{
if (view is TextView)
{
((TextView)view).Typeface = typeface;
}
if (view is ViewGroup)
{
ViewGroup viewgroup = (ViewGroup)view;
for (int i = 0; i < viewgroup.ChildCount; i++)
{
SetTypeFace(viewgroup.GetChildAt(i), typeface);
}
}
}
}