官术网_书友最值得收藏!

Changing layout properties during runtime

In Android development, it's generally the preferred practice to define the UI with XML and the application code in Java, keeping the User Interface code separate from the application code. There are times where it is much easier or more efficient, to alter (or even build) the UI from the Java code. Fortunately, this is easily supported in Android.

We saw a small example of modifying the layout from code in the previous recipe, where we set the number of GridView column to display in the code. In this recipe, we will obtain a reference to the LayoutParams object to change the margin during runtime.

Getting ready

Here we will set up a simple layout with XML and use a LinearLayout.LayoutParams object to change the margins of a View during runtime.

How to do it....

  1. Open the activity_main.xml file and change the layout from RelativeLayout to LinearLayout. It will look as follows:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </LinearLayout>
  2. Add a TextView and include an ID as follows:
    android:id="@+id/textView"
  3. Add Button and include an ID as follows:
    android:id="@+id/button"
  4. Open MainActivity.java and add the following code to the onCreate() method to set up an onClick event listener:
    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((TextView)findViewById(R.id.textView)).setText("Changed at runtime!");
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
            params.leftMargin += 5;
        }
    });
  5. Run the program on a device or emulator.

How it works...

Every View (and therefore ViewGroup) has a set of layout parameters associated with it. In particular, all Views have parameters to inform their parent of their desired height and width. These are defined with the layout_height and layout_width parameters. We can access this layout information from the code with the getLayoutParams() method. The layout information includes the layout height, width, margins, and any class-specific parameters. In this example, we moved the button on each click by obtaining the button LayoutParams and changing the margin.

主站蜘蛛池模板: 特克斯县| 三穗县| 博兴县| 桓仁| 花莲县| 乌审旗| 松江区| 富锦市| 阿拉善左旗| 沧州市| 綦江县| 威信县| 永康市| 田东县| 利川市| 浮山县| 彩票| 黄大仙区| 文山县| 鄂托克旗| 兴文县| 远安县| 南丰县| 武川县| 上虞市| 泗洪县| 临桂县| 广昌县| 莲花县| 怀化市| 吉木萨尔县| 凤台县| 常德市| 乌兰县| 航空| 白玉县| 兴安盟| 郯城县| 义马市| 瓮安县| 苏尼特右旗|