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

时间:2011-02-03 10:29:14

标签: android layout imageview

我有一个用布局文件编写的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>

如何在我的Activity中读取android:layout_marginLeft属性?

我尝试了以下代码,但我LayoutParams的{​​{1}}没有任何保证金成员(例如ImageView已有)。

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 获取保证金的任何建议吗?

谢谢!

2 个答案:

答案 0 :(得分:25)

您必须将LayoutParams强制转换为特定于该视图所在布局的类型。也就是说,作为LinearLayout内的视图,您必须执行以下操作:

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

现在lp将允许您访问margin*个字段。

答案 1 :(得分:6)

你的溶胶如下:


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

  int i=lp.leftMargin;