在您將我標記爲重複項並開始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