简体   繁体   English

如何以编程方式读取ImageView边距?

[英]How read ImageView margin programmatically?

I have an ImageView which is written in a layout file and looks like this 我有一个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>

How can I read the android:layout_marginLeft attribute in my Activity? 如何在Activity中读取android:layout_marginLeft属性?

I tried this following code but LayoutParams of my ImageView doesn't have any margin members (like for example LinearLayout.LayoutParams has). 我尝试了以下代码,但我的ImageView LayoutParams没有任何边距成员(例如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

Any suggestions how to get the margin from a ImageView ? 有关如何从ImageView获取边距的任何建议吗?

Thank you! 谢谢!

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: 您必须将LayoutParams转换为特定于视图所在布局的类型。也就是说,作为您在LinearLayout的视图,您必须执行以下操作:

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

now lp will let you access margin* fields. 现在lp将允许您访问margin*字段。

Your sol for it is as below: 你的溶胶如下:


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

  int i=lp.leftMargin;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM