Android动态设置view的大小及其位置

动态设置view的大小及其位置 【Android动态设置view的大小及其位置】需求就不说了,下面贴代码:
MainActivity
主要就是对view的操作,例如:

public class MainActivity extends Activity implements OnClickListener {private Button btn; private ImageView iv; private LinearLayout ll_group; public boolean isFullScreen = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); }private void initView() { btn = (Button) findViewById(R.id.btn); iv = (ImageView) findViewById(R.id.iv); ll_group = (LinearLayout) findViewById(R.id.ll_group); btn.setOnClickListener(this); }@Override public void onClick(View v) {if (isFullScreen) { // 全屏转半屏 setViewSize(iv); isFullScreen = false; } else { isFullScreen = true; setViewFullScreen(iv); }}/** * 设置view的大小 * * @param iv2 */ private void setViewFullScreen(ImageView view) { MarginLayoutParams margin = new MarginLayoutParams(view.getLayoutParams()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(margin); layoutParams.width = 1000 ; layoutParams.height = 800 ; view.setLayoutParams(layoutParams); }/** * 自定义设置位置及其大小 * * @param iv2 */ private void setViewSize(ImageView view) { MarginLayoutParams margin = new MarginLayoutParams(view.getLayoutParams()); int dpTop = dp2px( 10); int dpRight = dp2px( 10); int dpLeft=dp2px( 10); margin.setMargins(dpLeft, dpTop, dpRight, 0); DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(margin); layoutParams.width = 500; layoutParams.height= 400; view.setLayoutParams(layoutParams); } publicint dp2px(float dpValue){ final float scale=MainActivity.this.getResources().getDisplayMetrics().density; return (int)(dpValue*scale+0.5f); } }

xml

注意事项
动态变化的view设置宽高属性时,指向的引用类型,应该是该view的父控件。否则将会报:
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

MarginLayoutParams margin = new MarginLayoutParams(view.getLayoutParams()); /** *在xml中,view的父控件是LinearLayout这里要LinearLayout.LayoutParams. */ LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(margin); layoutParams.width = 1000 ; layoutParams.height = 800 ; view.setLayoutParams(layoutParams);

    推荐阅读