2011-02-03 35 views
11

Tôi có một ImageView được viết bằng một file layout và trông như thế nàyCách đọc ImageView margin theo lập trình?

<LinearLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 

     <ImageView android:id="@+id/news_image" 
      android:layout_height="fill_parent" 
      android:layout_width="fill_parent" 
      android:layout_marginLeft="18dip" 
      android:layout_marginRight="18dip" 
      android:background="#aaaaaa" /> 

</LinearLayout> 

Làm thế nào tôi có thể đọc các android: attribute layout_marginLeft trong Hoạt động của tôi?

Tôi đã thử mã sau đây nhưng LayoutParams trong số ImageView không có bất kỳ thành viên ký quỹ nào (ví dụ: LinearLayout.LayoutParams có).

ImageView imageView = (ImageView)findViewById(R.id.news_image); 
LayoutParams lp = imageView.getLayoutParams(); 

int marginLeft = lp.marginLeft; // DON'T do this! It will not work 
           // cause there is no member called marginLeft 

Bất kỳ lời đề nghị như thế nào để có được lợi nhuận từ một ImageView?

Cảm ơn bạn!

Trả lời

25

bạn phải cast LayoutParams để loại đó là cụ thể để bố trí các chế độ xem ở Nghĩa là, là quan điểm của bạn bên trong a. LinearLayout, bạn sẽ phải làm như sau:

ImageView imageView = (ImageView)findViewById(R.id.news_image); 
LinearLayout.LayoutParams lp = 
       (LinearLayout.LayoutParams) imageView.getLayoutParams(); 

tại lp sẽ cho phép bạn truy cập margin* lĩnh vực.

+0

Cảm ơn bạn! Những công việc này. Tôi không thể tìm thấy bất kỳ thứ gì trong tài liệu Android. Có lẽ tôi chỉ nhìn vào những chỗ sai. – OemerA

6

sol của bạn cho nó là như sau:


LinearLayout. LayoutParams lp = (android.widget.LinearLayout.LayoutParams) imageView.getLayoutParams(); 

    int i=lp.leftMargin; 
Các vấn đề liên quan