[英]Programmatically RelativeLayout.ALIGN_RIGHT with a given View.getId() not working
我嘗試以編程方式將TextView對齊到按鈕的右/下邊緣。 但是,這個靜態xml代碼正在工作:
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="@+id/textView10"
android:layout_alignRight="@+id/button"
android:layout_alignBottom="@+id/button" />
</RelativeLayout>
如果我嘗試通過代碼執行它,它不起作用。 默認情況下,TextView在頂部/左側對齊。 RelativeLayout.ALIGN_RIGHT和ALIGN_BOTTOM似乎被忽略了......
// Adding the LinearLayout
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
final LinearLayout.LayoutParams LLParamsCont = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, Utils.dpToPx(getContext(), 50));
// Adding the RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(getContext());
relativeLayout.setLayoutParams(LLParamsCont);
// Adding the Button
Button button = new Button(getContext());
button.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(button)
// Adding the TextView
TextView textView = new TextView(getContext());
textView.setGravity(Gravity.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
Utils.dpToPx(getContext(), 20),
Utils.dpToPx(getContext(), 20));
layoutParams.addRule(RelativeLayout.ALIGN_RIGHT, button.getId()); // <== THIS DOESN'T SEEM TO WORK
layoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, button.getId()); // <== THIS DOESN'T SEEM TO WORK
textView.setLayoutParams(layoutParams);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundResource(R.drawable.score_count);
relativeLayout.addView(textView);
linearLayout.addView(relativeLayout)
TextView只是沒有與Button的右/底行對齊。
有沒有人知道為什么不能通過代碼工作,但使用靜態xml? 我錯過了什么?
謝謝!
最誠摯的問候,Juergen
嘗試在創建規則之前為Button設置唯一ID ( 此處有更多信息)。
Button button = new Button(getContext());
button.setId(View.generateViewId()); //this utility method is API 17!
我在這篇文章中找到了解決方案: 如何以編程方式在RelativeLayout中布局視圖?
我需要將setId(int)的id設置為Button,然后才能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.