LayoutParams基本使用


LayoutParamsって何?
LayoutParamsは主にViewのレイアウトパラメータを保存しているので、LayoutParamsを使用してレイアウトパラメータを変更してView位置の効果を達成することができ、一般的にViewをカスタマイズする際に使用されます.
LayoutParamsはどうやって使いますか?
  • 親コントロールがLinearLayoutの場合、LinearLayout.LayoutParamsコードは次のとおりです:
  • LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)getLayoutParams();
    layoutParams.leftMargin=getLeft()+offsetX;
    layoutParams.topMargin=getTop()+offsetY;
    setLayoutParams(layoutParams)
  • 親コントロールがRelativeLayoutの場合、RelativeLayout.LayoutParamsを使用する必要があります.
  • RelativeLayout.LayoutParams layoutParams=(RelativeLayout.LayoutParams)getLayoutParams();
    layoutParams.leftMargin=getLeft()+offsetX;
    layoutParams.topMargin=getTop()+offsetY;
    setLayoutParams(layoutParams)
  • レイアウトのLayoutParamsを使用するほか、ViewGroup.MarginLayoutParamsを使用して実現できます.
  • ViewGroup.MarginLayoutParams layoutParams=(ViewGroup.MarginLayoutParams)getLayoutParams();
    layoutParams.leftMargin=getLeft()+offsetX;
    layoutParams.topMargin=getTop()+offsetY;
    setLayoutParams(layoutParams);
  • 親Viewを探す必要がない場合、自分でnewをカスタマイズします.
  • View line = null;
    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
    layoutParams.leftMargin = 10;
    line = new View(mContext);
    line.setBackgroundResource(R.color.color_tie_bg);
    addView(line, layoutParams);
    
  • は、WindowManager.LayoutParamsによって実現される.以下に、Windowサイズを設定するコードを取得する.例えば、Dialogをカスタマイズする際にonCreateメソッドでこのコードを記述し、dialogが最後にWindowを表示するサイズを設定する.
  •  Window win = getWindow();
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.height = DensityUtil.dip2px(mContext, 185);
            lp.width = DensityUtil.dip2px(mContext, 280);
            win.setAttributes(lp);

    まとめ
    以上は開発過程で使用したLayoutParamsに関する内容で、後期には絶えず補充されます.