2011-02-03 50 views
11

我這是寫在一個佈局文件,看起來像這樣如何以編程方式讀取ImageView邊距?

<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> 

我怎樣才能閱讀Android的ImageView的:layout_marginLeft屬性在我的活動?

我想這下面的代碼,但我ImageViewLayoutParams沒有任何餘量成員(例如像LinearLayout.LayoutParams有)。

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 

任何建議如何從ImageView獲得保證金?

謝謝!

回答

25

您必須將LayoutParams轉換爲特定於佈局的觀點是在類型也就是說,是內部的視圖。 LinearLayout,你就必須做到以下幾點:

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

現在lp將讓你訪問margin*領域。

+0

謝謝!這工作。我無法在Android文檔中找到任何內容。也許我只是看錯了地方。 – OemerA 2011-02-03 13:06:07

6

你爲它溶膠如下:


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

    int i=lp.leftMargin; 
相關問題