Button button = new Button(this); // create a new button button.setText("Click me"); // set button text RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ); // create layout parameters params.addRule(RelativeLayout.CENTER_IN_PARENT); // position button in center of parent view button.setLayoutParams(params); // set layout parameters to button
TextView textView = findViewById(R.id.myTextView); // get a reference to an existing text view LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) textView.getLayoutParams(); // get the existing layout parameters params.width = 200; // set width to 200 pixels params.height = 100; // set height to 100 pixels params.gravity = Gravity.CENTER_HORIZONTAL; // center the text view horizontally textView.setLayoutParams(params); // apply the updated layout parametersIn this example, an existing text view is retrieved using `findViewById`. The existing layout parameters are retrieved using `getLayoutParams`. The width, height, and gravity properties are modified, then the updated layout parameters are applied to the text view using `setLayoutParams`. The `setLayoutParams` method is part of the `android.view.View` class, which is included in the Android SDK. Therefore, the package library is `android.view`.