Layouts and views

Start by reading the User Interface section of the Android docs.

XML Layouts

Below is the XML layout file we demonstrated in class. I placed the youtube icon in the app/src/main/res/drawable resource directory.

Design view of the layout given below

Design view of the layout given below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.app.MainActivity$PlaceholderFragment">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </TextView>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        <ImageView
                android:src="@drawable/youtube"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        <Button android:text="Acknowledged"
                android:layout_width="wrap_content"
                   android:layout_height="wrap_content"/>
    </LinearLayout>
    <TextView
            android:text="NEW VIEW"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New Text"
            android:id="@+id/textView"/>

</LinearLayout>

IDs and events

When you give the widgets in your layout an id property such as @+id/helloText or @+id/clickMe, then you can access them from Java code. Here’s an example of how we made clicking the button change the text in a text view. All of it goes into the onCreateView method of the PlaceholderFragment in MainActivity.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main,
                                     container, false);
    // The new code:
    Button clickMe = (Button) rootView.findViewById(R.id.clickMe);
    final TextView helloText = (TextView)
        rootView.findViewById(R.id.helloText);
    Log.i("LogTest", "clickMe is " + clickMe);
    clickMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("LogTest", "You clicked the button!");
            helloText.setText("Thanks for clicking.");
        }
    });
    // End new code.
    return rootView;
}