如何找到layout_marginTop

时间:2013-03-11 18:50:20

标签: android android-layout

我有一个包含以下attritubes的XML文件:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/al_cs_layout1"
android:gravity="center_vertical">

<ImageView android:id="@+id/cs_track" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:background="@drawable/fader_background5"
android:layout_marginLeft="0dp"
android:layout_marginTop="20dp" >
</ImageView>
...

这是我的java代码:

public void initialize(Context context)
{
Log.d("initialize (MySeekBar)","initialize");
setWillNotDraw(false);

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view1 = inflater.inflate(R.layout.custom_seekbar, this);

layout1 = (RelativeLayout)view1.findViewById(R.id.al_cs_layout1);
track = (ImageView)layout1.findViewById(R.id.cs_track);
thumb = (ImageView)layout1.findViewById(R.id.cs_thumb);
...

我正在开发一个自定义搜索栏,它通过使用变量marginTop = 20来确定顶部;然而,这是由另一个程序员在更老的手机上制作的。 20假设代表XML中定义的边缘顶部,但它使用的是dp而不是像素。如何找到R.id.cs_track的marginTop属性?它在旧手机上运行良好,但在任何手机上都没有相同的dp屏幕尺寸,它会产生不希望的偏移。

1 个答案:

答案 0 :(得分:1)

使用MarginLayoutParams获取像素值:

track = (ImageView)layout1.findViewById(R.id.cs_track);
MarginLayoutParams params = (MarginLayoutParams)track.getLayoutParams();
int marginTopPixelSize = params.topMargin;