The code dynamically changes the size of the view implementation method, and the code dynamically views the size
The code dynamically changes the size of the view.
Background
Recently, we need to draw a square chart. I use a custom view, but the Zoom cannot be implemented. So we use a button to dynamically change the view size.
Code Implementation
First, my xml layout code is as follows:
The xml layout is shown as follows:
Then the MainActivity code is as follows:
Package com. example. pc_2.viewsizechangedemo; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. relativeLayout; import android. widget. textView; public class MainActivity extends Activity {private Button btn_change_size; private TextView TV _size_change; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // sets the layout file setViews () used by the activity; // controls initialize setListener (); // sets listener} private void setListener () {btn_change_size.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {// obtain the layout parameter RelativeLayout of the parent layout of the view to be changed. layoutParams params = (RelativeLayout. layoutParams) TV _size_change.getLayoutParams (); // set the width to 100dp params. width = DensityUtil. dp2px (MainActivity. this, 100); // set the height to 100dp params. height = DensityUtil. dp2px (MainActivity. this, 100); // reset the view based on the layout parameter settings (text view is used here, of course, other views are also common) TV _size_change.setLayoutParams (params) ;}});} private void setViews () {btn_change_size = (Button) findViewById (R. id. btn_change_size); TV _size_change = (TextView) findViewById (R. id. TV _size_change );}}
The last two comparison charts are shown as follows:
Okay. The size is changed!
Note:
Note the following method:
// Obtain the layout parameter RelativeLayout. LayoutParams params = (RelativeLayout. LayoutParams) TV _size_change.getLayoutParams () for the parent layout of the view to be changed ();
Why is the layout parameter a RelativeLayout. LayoutParams object? The parent layout of the textview is RelativeLayout. Therefore, when the parent layout of a view is Linearlayout, The Linearlayout. LayoutParams object is used. This is the end of the lecture. Thank you!
================================================================
A little bit of progress every day!Come on!