在ImageView上设置layout_marginTop?

时间:2014-09-14 08:01:21

标签: java android android-imageview

我有2个组件的Framelayout

  • 线性布局
  • ImageView的

我想将android:layout_marginTop="100dp"设置为Imageview以编程方式

Stackoverflow解决方案说:

ImageView imgv = (ImageView)findViewById(R.id.redLine);
FrameLayout frameLayout= (FrameLayout)findViewById(R.id.frameLayout);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frameLayout.getLayoutParams();
layoutParams.setMargins(100, 0, 0, 0);
imgv.setLayoutParams(layoutParams);

但是我得到了Cast异常:

  

ClassCastException:android.widget.LinearLayout $ LayoutParams不能   强制转换为android.widget.FrameLayout $ LayoutParams

问题

如何设置:android:layout_marginTop="100dp"Imageview(以编程方式)?

其他信息:

enter image description here

进口:

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

2 个答案:

答案 0 :(得分:1)

这是对您自己的解决方案稍微有点教育的答案:

LayoutParams始终是添加View(或ViewGroup)的容器类型。如果你愿意,它们与视图的“父母”有关。

在你的例子中:

  • FrameLayout已添加到LinearLayout,因此其布局参数类型为LinearLayout.LayoutParams
  • ImageView已添加到FrameLayout,因此其布局参数类型为FrameLayout.LayoutParams

有了这些信息,您应该能够推断出出现了什么问题。

Spoiler:你犯了一个常见错误,认为FrameLayout的布局参数类型为FrameLayout.LayoutParams。但是,由于它们与布局的相关,因此它们实际上是LinearLayout.LayoutParams类型。因此,类强制转换异常。

答案 1 :(得分:0)

知道了:

      FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      params.setMargins(200, 1, 1, 1);
      imgv.setLayoutParams(params);