问题
I used a FragmentTransaction to add a Fragment into a FrameLayout. I want to dynamically change the margin of the RelativeLayout used by the Fragment. However, the margins are not changing with RelativeLayout.layoutParams. I also used setMargins()
and it didnt work.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.infocard, container, false);
RelativeLayout infoLayout = (RelativeLayout) view.findViewById(R.id.info);
infoLayout.setOnClickListener(new EmptyClickListener());
final int width = 250;
final int height = 320;
int leftMargin = 0;
int topMargin = 0;
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
if (x - width < 0) {
leftMargin = 0;
System.out.println("left " + leftMargin);
}
else {
leftMargin = x - width;
}
if (y >= 450 && y <= 480) {
topMargin = y - height;
}
params.leftMargin = leftMargin;
params.topMargin = topMargin;
infoLayout.setLayoutParams(params);
回答1:
Try using
FrameLayout.LayoutParams
instead of
RelativeLayout.LayoutParams
Layouts expect the params type to be the type from their parent container rather than the View type that you are setting them on
来源:https://stackoverflow.com/questions/9811722/setting-margins-on-relative-layout-doesnt-work