Android Application Development Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Inserting a widget into a layout

As you may have seen from previous recipes, widgets are declared in a layout file, or created in code. For this recipe, we will go step-by-step to add a button with the Android Studio Designer. (For later recipes, we will just show the layout XML from the TextView.) After creating the button, we will create an onClickListener().

Getting ready

Start a new project in Android Studio and call it InsertWidget. Use the default options for creating a Phone and Tablet project and select Empty Activity when prompted for the Activity Type. You can delete the default TextView (or leave it) as it will not be needed for this recipe.

How to do it...

To insert a widget into a layout, follow these steps:

  1. Open the activity_main.xml file in Android Studio and click on the Design tab.
  2. Find Button in the widget list and drag it to the center of the activity screen on the right. Android will automatically set the layout parameters based on where the button is dropped. If you center the button as shown in the screenshot, Android Studio will set those parameters in the XML.
  3. To view the xml created, click on the Text tab as shown in the following screenshot. See how the button is centered using the RelativeLayout parameters. Also, take note of the default ID as we will need it for the next step.
  4. Now, open the MainActivity.java file to edit the code. Add the following code to the onCreate() method to set up the onClickListener():
    Button button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this,"Clicked",Toast.LENGTH_SHORT).show();
        }
    });
  5. Run the application on a device or emulator.

How it works...

Creating the UI with the Android Studio is as simple as dragging and dropping Views. You can also edit the properties of the Views directly in the Design tab. Switching to the XML code is as simple as hitting the Text tab.

What we did here is very common in Android development—creating the UI in XML, then hooking up the UI components (Views) in the Java code. To reference a View from code, it must have a resource identifier associated with it. This is done using the id parameter:

android:id="@+id/button"

Our onClickListener function displays a pop-up message on the screen called Toast, when the button is pressed.

There's more...

Take a look again at the format of the identifier we created previously, @+id/button. The @ specifies this is going to be a resource and the + sign indicates a new resource. (If we failed to include the plus sign, we would get a compile time error stating No resource matched the indicated name).

See also