【问题标题】:How to use the same UI instance across different layouts in Android如何在 Android 的不同布局中使用相同的 UI 实例
【发布时间】:2015-11-09 23:55:36
【问题描述】:
我有一个 UI 组件,比如一个按钮,它存在于我的应用程序的多个视图中。我正在使用单例方法来跟踪按钮的状态。此按钮位于这些不同视图中的不同位置。现在,我只是通过执行 (Button)findViewById($id_of_button) 在不同视图中引入尽可能多的按钮。然而,因为我希望这个特定的按钮在不同的视图中表现出相同的行为(启用等),我想知道是否有一种方法可以让我创建一个按钮实例并且只管理我的单例中的一个按钮目的。
【问题讨论】:
标签:
android
user-interface
layout
static
singleton
【解决方案1】:
在单独的布局(R.layout.universalButton)中声明您的按钮,然后您可以使用 LayoutInflater 的 inflate 方法将其作为任何 ViewGroup(LinearLayout、RelativeLayout 等)的子项:
View button=activity.getLayoutInflater().inflate(R.layout.universalButton, viewGroup, false);
button.setOnClickListener(listener);
viewGroup.addView(button);
您也可以使用include 语句将其包含在 XML 中的任何位置
<include layout="@layout/universalButton" android:name="button1" />
<include layout="@layout/universalButton" android:name="button2" />
请注意,一个按钮总是会有多个实例,因为一个视图只能有一个父级!