Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How read ImageView margin programmatically?

I have an ImageView which is written in a layout file and looks like this

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

How can I read the android:layout_marginLeft attribute in my Activity?

I tried this following code but LayoutParams of my ImageView doesn't have any margin members (like for example LinearLayout.LayoutParams has).

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

Any suggestions how to get the margin from a ImageView?

Thank you!

like image 684
OemerA Avatar asked Feb 03 '11 10:02

OemerA


2 Answers

you have to cast the LayoutParams to the type that is specific to the layout the view is in. That is, being your view inside a LinearLayout, you'll have to do the following:

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

now lp will let you access margin* fields.

like image 163
bigstones Avatar answered Sep 27 '22 21:09

bigstones


Your sol for it is as below:


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

  int i=lp.leftMargin;
like image 27
chikka.anddev Avatar answered Sep 27 '22 22:09

chikka.anddev