- A GridView layout positions widgets in a rectangular grid.
- Widgets in the grid can occupy multiple rows or columns.
- Create an Android Studio project named PhoneButtons.
- Change the layout to GridView. Here is the start node for our
GridView layout:
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:rowCount="5"
android:columnCount="3"
android:padding="40dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
- Place a TextView widget in the top row (row 0) of the grid view:
<TextView
android:id="@+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="3"
android:layout_row="0"
android:layout_column="0"
android:text="@string/empty" />
- Place buttons in rows 1 to 4. Here is what the layout looks like in the
emulator.
- Place buttons in rows 1 to 4. Here is the node for the button with text 1
in Row=1, Column=0:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="0"
android:text="@string/digit1"
android:onClick="onClick" />
- In the Java Activity code, set up an event handler so that whenever a digit
is pressed, the digit is concatenated to the phone number in the text view.
When the button with the R digit is pressed, clear the text view. Here is the
Java activity code:
package it372.phonebuttons;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private String phoneNumber = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onClick(View view) {
TextView tv = (TextView) findViewById(R.id.phone_number);
Button btn = (Button) view;
String digit = btn.getText( ).toString( );
if (digit.equals("R")) {
phoneNumber = "";
}
else {
phoneNumber += digit;
}
tv.setText(phoneNumber);
}
}
- Add this line to the app/src/main/res/values/styles.xml file:
<item name="android:textSize">30sp</item>d:onClick="onClick" />
This increases the text size in
the text view and buttons to 30sp.