2012-05-02 37 views
51

Bạn có thể cho tôi một ví dụ rất đơn giản về việc thêm chế độ xem con theo chương trình vào RelativeLayout tại một vị trí nhất định không?Cách thêm chế độ xem theo chương trình vào RelativeLayout?

Ví dụ, để phản ánh XML sau:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"> 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_alignParentTop="true" 
    android:layout_marginLeft="107dp" 
    android:layout_marginTop="103dp" 
    android:text="Large Text" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

Tôi không hiểu làm thế nào để tạo ra một RelativeLayout.LayoutParams dụ thích hợp.

Trả lời

91

Heres một ví dụ để giúp bạn bắt đầu, điền vào phần còn lại có thể áp dụng:

TextView tv = new TextView(mContext); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
params.leftMargin = 107 
... 
mRelativeLayout.addView(tv, params); 

Các tài liệu cho RelativeLayout.LayoutParams và các nhà thầu đang here

+0

Xin lỗi, cùng một câu hỏi: bạn đã tìm hiểu về hàm tạo 'RelativeLayout.LayoutParams' mà không có tham số' Context' làm thông số đầu tiên ở đâu? –

+1

@SuzanCioc Xem chỉnh sửa ở trên – JRaymond

+0

Ah, xin lỗi đã suy nghĩ chiều rộng và chiều cao phải là giá trị chính xác. –

27

Thứ nhất, bạn nên đưa ra một id để bạn RelativeLayout hãy nói relativeLayout1.

RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.relativeLayout1); 
TextView mTextView = new TextView(context); 
mTextView.setText("Dynamic TextView"); 
mTextView.setId(111); 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); 
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 
mainLayout.addView(mTextView, params); 
+0

Phương thức khởi tạo 'RelativeLayout.LayoutParams' được mô tả ở đâu? Nó không có ở đây http://developer.android.com/reference/android/widget/RelativeLayout.html vì tất cả các nguyên mẫu có 'Context' làm tham số đầu tiên. –

+1

Bạn nên kiểm tra tại đây http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html Đó là RelativeLayout.LayoutParams (int w, int h) –

+0

'R.id.relativeLayout1' là gì liên quan đến? – Si8

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