在您将我标记为重复项并开始downvotes滚动之前,请知道我正在尽我所能在这里完成这项工作将近3个小时。我已经尝试了四种不同的方法,我在Docs和各种论坛主题上阅读过。如何在Android中正确模板化/ xml重用
我有Button
我在独立xml
文件看起来像这样定义的:
<!--button_template.xml-->
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/score_question_btn"
android:onClick="viewScore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:padding="24dp" />
我想用它来动态填充视图。
我迄今为止尝试:
context.findViewById(R.id.button_id);
这是不行的,因为按钮是不是当前上下文根视图的子视图,从而返回null
LayoutInflator
- >inflate(R.layout.button_template.xml, rootView, false);
我可以”不要使用它,因为我需要为特定的按钮设置不同的文本和背景颜色。- 的
style resource
使用自定义,定义margins
,但我无法找到一个方法来设置Button style
Button button = new Button(context)
简单地说,我不能得到这个工作。我创建了Button
,我可以很容易地设置文本和颜色,但是然后有一个margins
的问题。
后半小时试图穿上Button
吓坏margin
,我想出了这个:
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
int dpMargin = 16;
float d = context.getResources().getDisplayMetrics().density;
int marginInPixels = (int) (dpMargin * d);
params.setMargins(marginInPixels, marginInPixels, marginInPixels, 0);
但是,我不知道是否可行,因为这是一贯崩溃我的项目。它执行一次,崩溃,然后我无法启动我的项目,因为它找不到我的MainActivity class
。我也花了一个小时跟踪这个。我想出的唯一修复方法是将我的src
文件夹复制到新项目中。
所以关于这个问题:我在正确的轨道上?如果是这样我做错了什么?如果不是的话 - 一个有经验的android开发人员将如何处理这个模板问题。
“因为我需要为特定按钮设置不同的文本和背景颜色” - 您可以调用Button实例上的Java方法来设置此信息。 – CommonsWare
我不确定我是否理解你想要达到的目标......你说“我想用它来动态地填充一个视图。”我想你正在尝试创建一个按钮布局xml,并在应用程序的其他部分/其他布局,一些线性布局等内部重用该按钮? – ramden