BCA / B.Tech 13 min read

Screen Orientation and the Action Bar

Screen Orientation and the Action Bar

1: Adapting to and Managing Screen Orientation

What is Screen Orientation?

Screen orientation refers to the physical orientation of the device. There are two main orientations in Android:

  • Portrait: The device is held upright (vertically).
  • Landscape: The device is held sideways (horizontally).

The Problem with Orientation Change

By default, when the user rotates the device, Android destroys the current activity and then recreates it. This is done so that the app can load alternative resources (like a special layout for landscape mode).

The Problem: During this process, the current state of the activity (like text in an `EditText` or the value of a counter) is lost.

How to Manage Orientation Changes

1. Saving and Restoring State (Recommended)

This is the best way to handle the activity state.

  • onSaveInstanceState(): This method is called just before the activity is about to be destroyed. You can save temporary data in a `Bundle` object here.
  • onCreate() or onRestoreInstanceState(): When the activity is recreated, the saved `Bundle` is available in the `onCreate()` method, from where you can restore the data.

Example in Java:


public class MainActivity extends AppCompatActivity {
    private int counter = 0;
    private TextView counterTextView;
    static final String STATE_COUNTER = "counterState";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        counterTextView = findViewById(R.id.counter_tv);

        // Check if there is a saved state
        if (savedInstanceState != null) {
            counter = savedInstanceState.getInt(STATE_COUNTER);
        }
        counterTextView.setText(String.valueOf(counter));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // Save the value of the counter
        outState.putInt(STATE_COUNTER, counter);
        
        // Always call the superclass method
        super.onSaveInstanceState(outState);
    }
    
    // Assume the counter increments on a button click
    public void incrementCounter(View view) {
        counter++;
        counterTextView.setText(String.valueOf(counter));
    }
}

2. Locking the Orientation

If you want your app to run in only one orientation, you can lock it in the `AndroidManifest.xml` file.


<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"> 
    <!-- or "landscape" -->
</activity>

2: Utilizing the Action Bar

What is the Action Bar (or Toolbar)?

The Action Bar (referred to as `Toolbar` or `AppBar` in modern apps) is a UI component at the top of the screen. It displays your app's branding (logo/title) and provides access to important actions for the user (like search, settings, share).

Key Parts of the Action Bar:

  • App Icon: The app's icon or logo.
  • Title: The title of the activity.
  • Action Items: Clickable icons that perform common actions in the app.
  • Overflow Menu: The three-dot menu that holds less-frequently used actions.

How to Add Items to the Action Bar

Action bar items are defined in a menu resource file (XML).

Step 1: Create a Menu XML File

1. Right-click the `res` folder > New > Android Resource Directory. Choose `menu` as the directory name.
2. Right-click the `res/menu` folder > New > Menu Resource File. Give it a name (e.g., `main_menu.xml`).

Example of `main_menu.xml`:


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        android:title="Search"
        app:showAsAction="ifRoom" /> 
        <!-- ifRoom means show it if there is space, otherwise put it in the overflow menu -->

    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        app:showAsAction="never" />
        <!-- never means always show it in the overflow menu -->

</menu>

Step 2: Inflate the Menu in the Activity

Override the `onCreateOptionsMenu()` method in your activity's Java file.


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

Step 3: Handle Menu Item Clicks

When the user clicks an action item, the `onOptionsItemSelected()` method is called.


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    int id = item.getItemId();

    if (id == R.id.action_search) {
        Toast.makeText(this, "Search clicked", Toast.LENGTH_SHORT).show();
        return true;
    } else if (id == R.id.action_settings) {
        Toast.makeText(this, "Settings clicked", Toast.LENGTH_SHORT).show();
        return true;
    }

    return super.onOptionsItemSelected(item);
}