2015-02-06 16 views
3

我尝试以编程方式将TextView对齐按钮的右侧/底部边缘。 但是,这种静态的XML代码工作:以编程方式RelativeLayout.ALIGN_RIGHT与给定的View.getId()不起作用

<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的是不beeing对齐按钮右侧/底线。

有没有人有一个想法,为什么这是不工作的代码,但与静态XML? 我错过了什么?

谢谢!

与问候, 克林斯曼

+0

你好,如果你删除这两行中的'+',xml是否仍然有效? android:layout_alignRight =“@ + id/button” android:layout_alignBottom =“@ + id/button”' – Poutrathor 2015-02-06 16:31:46

回答

2

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

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

谢谢,刚刚发布在同一秒内。但你是对的,我需要设置一个id到按钮。 – Juwei 2015-02-06 16:35:16

相关问题