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

Oem*_*erA 11 layout android 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>
Run Code Online (Sandbox Code Playgroud)

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

我尝试了以下代码,但LayoutParamsImageView没有任何保证金成员(例如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
Run Code Online (Sandbox Code Playgroud)

ImageView什么建议如何获得保证金?

谢谢!

big*_*nes 25

你必须转换LayoutParams为特定于视图所在布局的类型.也就是说,作为你在a中的视图LinearLayout,你必须执行以下操作:

ImageView imageView = (ImageView)findViewById(R.id.news_image);
LinearLayout.LayoutParams lp =
                (LinearLayout.LayoutParams) imageView.getLayoutParams();
Run Code Online (Sandbox Code Playgroud)

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


chi*_*dev 6

你的溶胶如下:


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

  int i=lp.leftMargin;
Run Code Online (Sandbox Code Playgroud)