MainActivity如下:
package cc.c; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout.LayoutParams; /** * Demo描述: * LayoutParams使用示例 * 利用getLayoutParams()和setLayoutParams()获取和设置控件的布局 */ public class MainActivity extends Activity { private Button mFirstButton; private Button mSecondButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mFirstButton=(Button) findViewById(R.id.firstButton); mSecondButton=(Button) findViewById(R.id.secondButton); mFirstButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //1 获取到LayoutParams LayoutParams layoutParams= (LayoutParams) mSecondButton.getLayoutParams(); //2 修改LayoutParams layoutParams.width=300; layoutParams.height=100; layoutParams.leftMargin=150; layoutParams.topMargin=300; //3 重新设置LayoutParams mSecondButton.setLayoutParams(layoutParams); } }); } }
main.xml如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/firstButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="firstButton" /> <Button android:id="@+id/secondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="100dip" android:text="secondButton" /> </LinearLayout>
时间: 2024-09-15 16:55:22