gpt4 book ai didi

java - 以编程方式 RelativeLayout.ALIGN_RIGHT 与给定的 View.getId() 不工作

转载 作者:太空狗 更新时间:2023-10-29 13:21:21 24 4
gpt4 key购买 nike

我尝试以编程方式将 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 工作?我错过了什么?

谢谢!

谨致问候,于尔根

最佳答案

尝试在创建规则之前为按钮设置一个唯一的 id(更多信息 here)。

Button button = new Button(getContext());
button.setId(View.generateViewId()); //this utility method is API 17!

关于java - 以编程方式 RelativeLayout.ALIGN_RIGHT 与给定的 View.getId() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com