Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MohammadSamandari/7b97fbba4d7b19d031424d8f3d27f560 to your computer and use it in GitHub Desktop.
Save MohammadSamandari/7b97fbba4d7b19d031424d8f3d27f560 to your computer and use it in GitHub Desktop.
Android ( menu - dialog - Picker - Fragment )

Menus and pickers

Menu

  1. we created a folder in res names menu
  2. we created a menu resource file and designed the menu.
  3. Infiltrate the menu to the activity that we want the menu in
        @Override
        public boolean onCreateOptionsMenu (Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main_activity_menu, menu);
            return true;
        }
  4. we can access the items which is selected with following codes:
    @Override
    public boolean onOptionsItemSelected (@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_btn_setting:
                //Do Something
                Log.d(TAG, "onOptionsItemSelected: ");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

Alert Dialog

You can provide a dialog to request a user's choice, such as an alert that requires users to tap OK or Cancel. A dialog is a window that appears on top of the display or fills the display, interrupting the flow of activity.

        //This function is going to open an alert dialog and ask for user choice:
        new AlertDialog.Builder(this)
                .setTitle("This is a dialog")
                .setMessage("Yes Or No?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        Log.d(TAG, "onClick: Yes");
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick (DialogInterface dialog, int which) {
                        Log.d(TAG, "onClick: NO");
                    }
                })
                .show();

Use a picker for user input & Fragments

Android provides ready-to-use dialogs, called pickers, for picking a time or a date. You can use them to ensure that your users pick a valid time or date that is formatted correctly and adjusted to the user's local time and date. Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year). You can read all about setting up pickers in Pickers.

learn how to use a Fragment, which is a behavior or a portion of a UI within an Activity. It's like a mini-Activity within the main Activity, with its own lifecycle, and it's used for building a picker.

The best practice to show a picker is to use an instance of DialogFragment, which is a subclass of Fragment. A DialogFragment displays a dialog window floating on top of the Activity window.

  1. we created a blank fragment without xml file or factory methods and named it DatePickerFragment
  1. Created a DatePicker Dialog in the fragment Visit DatePickerFragment for the code
  2. Modify the main activity you need to add a method that creates an instance of FragmentManager to manage the Fragment and show the date picker.
  3. get the date inside the onDateSet() method inside the fragment.
package mohammad.samandari.menu_dialog_datepicker_demo;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
import static android.content.ContentValues.TAG;
/**
* A simple {@link Fragment} subclass.
*/
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
public DatePickerFragment () {
// Required empty public constructor
}
@NonNull
@Override
public Dialog onCreateDialog (@Nullable Bundle savedInstanceState) {
// Use the current date as the default date in the picker.
Calendar c = Calendar.getInstance();
int YEAR = c.get(Calendar.YEAR);
int MONTH = c.get(Calendar.MONTH);
int DAY = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it.
return new DatePickerDialog(getActivity(), this, YEAR, MONTH, DAY);
}
@Override
public void onDateSet (DatePicker view, int year, int month, int dayOfMonth) {
//This override is run after the date is set.
MainActivity activity = (MainActivity) getActivity();
activity.ShowSelectedDate(year, month, dayOfMonth);
}
}
package mohammad.samandari.menu_dialog_datepicker_demo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.time.Year;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu (Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected (@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_btn_setting:
//Do Something
Log.d(TAG, "onOptionsItemSelected: ");
return true;
}
return super.onOptionsItemSelected(item);
}
public void openDialog (View view) {
//This function is going to open an alert dialog and ask for user choice:
new AlertDialog.Builder(this)
.setTitle("This is a dialog")
.setMessage("Yes Or No?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick (DialogInterface dialog, int which) {
Log.d(TAG, "onClick: Yes");
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick (DialogInterface dialog, int which) {
Log.d(TAG, "onClick: NO");
}
})
.show();
}
public void datePicker (View view) {
//This Function is going to show a date picker.
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void ShowSelectedDate (int year, int month, int day) {
String YEAR = String.valueOf(year);
String MONTH = String.valueOf(month + 1);
String DAY = String.valueOf(day);
Log.d(TAG, "ShowSelectedDate: " + YEAR + "-" + MONTH + "-" + DAY);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment