2013-06-02 37 views
6

Làm cách nào để thêm lập trình đường viền vào LinearLayout? Cho phép nói rằng chúng tôi tạo bố cục này:Lập trình thêm đường biên vào LinearLayout

LinearLayout TitleLayout = new LinearLayout(getApplicationContext()); 
TitleLayout.setOrientation(LinearLayout.HORIZONTAL); 

Sau đó, tôi phải làm gì?

+0

Bạn nên chấp nhận câu trả lời Sjoerd Van Den Berg. :-) – Alex

Trả lời

32

Tôi tin rằng câu trả lời ở trên là không đúng: Câu hỏi đặt ra yêu cầu đặc biệt cho một phiên bản chương trình để làm điều đó và điều đầu tiên bạn thấy là xml. Thứ hai, làm một phần xml là trong trường hợp của tôi hầu như không bao giờ một lựa chọn, vì vậy đây là câu trả lời đúng:

//use a GradientDrawable with only one color set, to make it a solid color 
    GradientDrawable border = new GradientDrawable(); 
    border.setColor(0xFFFFFFFF); //white background 
    border.setStroke(1, 0xFF000000); //black border with full opacity 
    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
     TitleLayout.setBackgroundDrawable(border); 
    } else { 
     TitleLayout.setBackground(border); 
    } 
+0

Làm thế nào để có hai màu sắc của Gradient drawable? –

4

Tạo XML gọi border.xml trong thư mục drawable như sau:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item> 
    <shape android:shape="rectangle"> 
     <solid android:color="#FF0000" /> 
    </shape> 
    </item> 
    <item android:left="5dp" android:right="5dp" android:top="5dp" > 
    <shape android:shape="rectangle"> 
     <solid android:color="#000000" /> 
    </shape> 
    </item>  
</layer-list> 

sau đó thêm này để bố trí tuyến tính như backgound như thế này:

android:background="@drawable/border" 

lập trình

TitleLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border)) 

CHỈNH SỬA:

Kể từ Jelly Bean, phương pháp này (setBackgroundDrawable đã bị phản đối), vì vậy nhưng bạn phải sử dụng cái này:

TitleLayout.setBackground(getResources().getDrawable(R.drawable.border)); 

hy vọng sự giúp đỡ này.

+0

Tôi đã thử nó. Nó không hoạt động. Ngoài ra eclipse nói rằng setBackgroundDrawable() không được chấp nhận. –

+0

Nó hoạt động, Eclipse chỉ nói rằng đó là không được chấp nhận bởi vì nó tồn tại một phương pháp khác kể từ Jelly Bean là: TitleLayout.setBackground (getResources(). GetDrawable (R.drawable.border)); –

+0

Tôi đã sử dụng "btn_tod.setBackgroundDrawable (new ColorDrawable (R.drawable.nobottom));" với các hiệu ứng lạ, giải pháp của MDMalik đã làm việc "btn_tod.setBackgroundDrawable (getResources(). getDrawable (R.drawable.nobottom));". Tôi không hiểu tại sao "new ColorDrawable" không hoạt động trong khi "getDrawable" hoạt động. Dường như "mới ColorDrawable" hoạt động cho các màu tùy chỉnh nhưng không cho các bản vẽ XML. –

Các vấn đề liên quan