我有一个用布局文件编写的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
获取保证金的任何建议吗?
谢谢!
答案 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;