2015-02-06 15 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

相關問題