获取textView边距并以编程方式设置ImageView边距。

时间:2017-11-15 11:16:53

标签: android android-imageview margin

在我目前的活动中,我试图获得ImageView的边距并在TextView中写入,但我总是收到" 0"。最高保证金约为390px。

final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
int a = Brick_1.getTop();

TextView t = (TextView) findViewById(R.id.tekstas);
t.setText(a+"");

2 个答案:

答案 0 :(得分:2)

从视图中获取边距。使用以下代码:

final ImageView Brick_1 = (ImageView)findViewById(R.id.Brick_1);
    ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) Brick_1.getLayoutParams();
    int marginTop =  lp.topMargin ;

将边距设置为视图。使用以下代码:

   TextView t = (TextView) findViewById(R.id.tekstas);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    /** @Firstparam - left margin
     *  @Second param - top margin
     *  @Third param - right margin
     *  @fourth param - bottom margin
     */
    lp.setMargins(0,marginTop,0, 0);
    t.setLayoutParams(layoutParams);

答案 1 :(得分:0)

您可以这样使用:

LinearLayout.LayoutParams lp =(LinearLayout.LayoutParams) Brick_1.getLayoutParams();

int margin = lp.topMargin;