Generate Unit 3 Answer Easy (Android)
Generate Unit 3 Answer Easy (Android)
UNIT-III
2 Marks Questions
1. Differentiate Views and ViewGroups Views are the basic building blocks of the user
interface in Android, such as buttons, text fields, and images. ViewGroups are invisible
containers that hold and organize other Views and ViewGroups, defining their layout on
the screen.
2. Define Views in Android. Give an example. Views in Android are the fundamental UI
elements that users see and interact with. They are typically drawn on the screen and
handle events. An example is a TextView which displays text.
3. Define ViewGroups in Android. Give an example. ViewGroups are special types of
Views that can contain other Views (and other ViewGroups). They are used to define the
layout structure of the UI. An example is a LinearLayout which arranges its children in a
single row or column.
4. List any four Layouts available in Android Four layouts available in Android are:
○ LinearLayout
○ RelativeLayout
○ FrameLayout
○ TableLayout
5. List any four common Attributes used in Views and ViewGroups Four common
attributes used in Views and ViewGroups are:
○ android:layout_width
○ android:layout_height
○ android:id
○ android:padding
6. What is a FrameLayout in Android? Specify its purpose. A FrameLayout is a
ViewGroup that is designed to block out an area on the screen to display a single item. If
you add multiple children to a FrameLayout, they will be drawn on top of each other,
overlapping. Its purpose is to efficiently display a single child view, or multiple children
stacked on top of each other.
7. What is a LinearLayout in Android? Specify its purpose A LinearLayout is a
ViewGroup that arranges its child views in a single row or a single column. Its purpose is
to organize UI elements either horizontally or vertically.
8. What is the purpose of TableLayout in Android UI design. Specify how to define
rows and columns in a TableLayout? The purpose of TableLayout is to arrange
elements into rows and columns, similar to an HTML table. Rows are defined using
TableRow elements, and columns are defined implicitly by the number of views within
each TableRow.
9. What is RelativeLayout in Android? How does RelativeLayout arrange its child
views? RelativeLayout is a ViewGroup that displays child views in relative positions. It
arranges its child views based on relationships with sibling views or with the parent
RelativeLayout itself. Views can be positioned to the left of, right of, above, below, or
aligned with other views or the parent's edges.
10.List any four attributes that enable a view to align with another view. Four attributes
that enable a view to align with another view in a RelativeLayout are:
○ android:layout_toRightOf
○ android:layout_below
○ android:layout_alignTop
○ android:layout_alignLeft
11.What is FrameLayout in Android? Specify the purpose of FrameLayout in Android
UI design. A FrameLayout is a ViewGroup that is designed to block out an area on the
screen to display a single item. Its purpose in Android UI design is to act as a placeholder
for a single view, or to stack multiple views on top of each other when layering is needed.
12.What is ScrollView in Android? Specify its purpose in Android UI design. A
ScrollView is a FrameLayout that allows a scrollable list of items. Its purpose in Android UI
design is to enable content that is larger than the screen to be scrolled, ensuring that all
content is accessible to the user.
13.Define TextView view in Android. List any two important XML attributes of it. A
TextView is a UI widget that displays text to the user. Two important XML attributes are:
○ android:text (to set the text content)
○ android:textSize (to set the size of the text)
14.Define EditText view in Android. List any two important XML attributes of it. An
EditText is a UI widget that allows users to input and modify text. It is a subclass of
TextView configured for user input. Two important XML attributes are:
○ android:hint (to provide a hint text when the field is empty)
○ android:inputType (to specify the type of input expected, e.g., "text", "number",
"password")
15.Define Button view. Give XML code snippet that define a Button. A Button view is a
UI widget that users can tap to perform an action.
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
16.Define CheckBox view. List any two important XML attributes of it. A CheckBox view
is a UI widget that allows a user to select one or more options from a set. Two important
XML attributes are:
○ android:text (to set the text label for the checkbox)
○ android:checked (to set the initial checked state of the checkbox, true or false)
17.Define RadioButton view. List any two important XML attributes of it. A RadioButton
view is a UI widget that allows a user to select one option from a set, where only one
radio button within a RadioGroup can be selected at a time. Two important XML attributes
are:
○ android:text (to set the text label for the radio button)
○ android:checked (to set the initial checked state of the radio button, true or false)
18.Define ImageButton view. Specify XML attributes used to set image and description
to it. An ImageButton view is a UI widget that displays an image and behaves like a
button. The XML attributes used to set the image and description are:
○ android:src (to set the drawable resource for the image)
○ android:contentDescription (to provide a textual description of the image for
accessibility)
19.Define ToggleButton view. Specify XML attributes used to set the ON and OFF text
to be displayed when the state of it changes. A ToggleButton view is a UI widget that
displays a light-switch-like button with two states: ON and OFF. The XML attributes used
to set the ON and OFF text are:
○ android:textOn (text to display when the button is in the ON state)
○ android:textOff (text to display when the button is in the OFF state)
20.Define ListView view. List any two important XML attributes of it. A ListView is a UI
widget that displays a scrollable list of items. Two important XML attributes are:
○ android:id (to uniquely identify the ListView)
○ android:layout_height (to specify the height of the ListView)
21.Define SpinnerView view. List any two important XML attributes of it. A SpinnerView
(commonly referred to as Spinner) is a UI widget that provides a quick way to select one
value from a set. Two important XML attributes are:
○ android:id (to uniquely identify the Spinner)
○ android:entries (to refer to an array resource containing the items to be displayed in
the spinner)
22.Define DialogFragment. Specify its use. DialogFragment is a special type of Fragment
that displays a dialog window. Its use is to display modal dialogs that float above the
activity's window, providing a way to prompt the user for input or display important
information without leaving the current activity.
4-6 Marks Questions
1. Describe the concept of a FrameLayout in Android and compare it with other layout
types like LinearLayout and RelativeLayout in terms of functionality and usage. A
FrameLayout is the simplest ViewGroup in Android, primarily designed to display a single
child view. If multiple children are added, they are drawn on top of each other in a stack,
with the last added view appearing on top.Comparison:
○ Functionality:
■ FrameLayout: Best for displaying a single view or for overlapping views. It
provides no inherent structure for positioning multiple children besides
stacking them.
■ LinearLayout: Arranges views in a single row (horizontal) or a single column
(vertical). It's ideal for linear arrangements and simpler layouts.
■ RelativeLayout: Positions views based on relationships to sibling views or
the parent. It's powerful for complex, non-linear layouts where elements need
to align with each other or with edges.
○ Usage:
■ FrameLayout: Common use cases include hosting a Fragment, displaying a
single image with a caption overlaid, or creating a custom view that needs to
draw multiple layers.
■ LinearLayout: Frequently used for forms, lists of items, or any UI where
elements need to be stacked or laid out in a sequence.
■ RelativeLayout: Useful for designing UIs where elements' positions depend
on others, like placing a button below a text field and aligning it to the right, or
centering an element within the parent.
In essence, FrameLayout offers basic layering, LinearLayout offers sequential
arrangement, and RelativeLayout offers flexible, relative positioning.
2. Discuss the difference between horizontal and vertical LinearLayout in Android.
Provide an example scenario where each orientation is suitable and explain how
you would implement it programmatically. LinearLayout arranges child views in a
single direction, either horizontally or vertically. The difference lies in the value of the
android:orientation attribute.
○ Horizontal LinearLayout:
■ Difference: Child views are placed next to each other from left to right (or
right to left in RTL locales).
■ Suitable Scenario: A toolbar at the top of an app containing several icons
(e.g., search, share, settings) placed side-by-side.
■ Implementation (XML):
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_search"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_share"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_settings"/>
</LinearLayout>
○ Vertical LinearLayout:
■ Difference: Child views are stacked on top of each other from top to bottom.
■ Suitable Scenario: A simple login form with an EditText for username, an
EditText for password, and a Button for login, all stacked vertically.
■ Implementation (XML):
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"/>
</LinearLayout>
3. android:id:
■ Purpose: Provides a unique identifier for the view within the layout. This ID is
used to reference the view programmatically in Java/Kotlin code.
■ Values: @+id/your_id_name for defining a new ID, or @id/existing_id_name
for referencing an existing ID.
■ Example:
<EditText
android:id="@+id/username_input"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
4. android:padding:
■ Purpose: Specifies the amount of space between the content of the view and
its boundaries. This creates internal spacing.
■ Values: A dimension (e.g., "16dp"). You can also use paddingLeft,
paddingRight, paddingTop, paddingBottom for specific sides.
■ Example:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Padded Text"
android:padding="20dp"/>
5. Compare and contrast Table Layout with LinearLayout and RelativeLayout in terms
of their layout capabilities and use cases. TableLayout:
○ Layout Capabilities: Arranges elements in rows and columns, similar to a
spreadsheet or HTML table. Columns are implicitly created by the number of views
in a TableRow. Cells in the same column are aligned. Columns can be stretched or
shrunk.
○ Use Cases: Ideal for displaying data in a grid-like format where alignment across
columns is crucial, like displaying tabular data, settings screens with two columns
(label and value), or simple forms.
LinearLayout:
○ Layout Capabilities: Arranges views in a single linear fashion (either horizontal or
vertical). Child views are positioned sequentially.
○ Use Cases: Best for simple stacks of elements (e.g., a list of buttons) or single
rows of elements (e.g., a toolbar). It's straightforward for basic, one-dimensional
layouts.
RelativeLayout:
○ Layout Capabilities: Positions views based on their relationship to other views or
to the parent container. This allows for complex and arbitrary positioning.
○ Use Cases: Highly flexible for non-linear, free-form layouts where elements need to
be precisely positioned relative to each other or to screen edges. Can minimize
nesting in complex designs.
Comparison/Contrast:
○ Structure:
■ TableLayout imposes a rigid grid structure of rows and columns.
■ LinearLayout offers a simple one-dimensional row or column structure.
■ RelativeLayout offers the most flexible, non-grid, non-linear positioning based
on relationships.
○ Alignment:
■ TableLayout excels at column-based alignment.
■ LinearLayout aligns items along its single axis.
■ RelativeLayout provides various alignment options relative to other views or
the parent.
○ Complexity: LinearLayout is the simplest. TableLayout is simple for tabular data
but can become complex if not purely tabular. RelativeLayout can be complex to
define but often leads to flatter hierarchies.
○ Best Fit: TableLayout for strict tabular data; LinearLayout for simple lists/stacks;
RelativeLayout for complex, arbitrary positioning.
6. Demonstrate how to create a Table Layout with three rows and three columns, each
containing TextView elements, in XML.
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"> <TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 1, Col 1"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 1, Col 2"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 1, Col 3"
android:padding="8dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 2, Col 1"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 2, Col 2"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 2, Col 3"
android:padding="8dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 3, Col 1"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 3, Col 2"
android:padding="8dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 3, Col 3"
android:padding="8dp"/>
</TableRow>
</TableLayout>
7. Demonstrate how to create a RelativeLayout with two TextView elements, where
one is aligned to the top-left corner and the other is positioned below and to the
right of the first TextView, in XML.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top-Left Text"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:padding="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Below and Right Text"
android:layout_below="@id/textView1"
android:layout_toEndOf="@id/textView1"
android:padding="16dp" />
</RelativeLayout>
10.Explain TextView view with any four notable XML attributes. A TextView is a UI
element used to display static text to the user. It is one of the most fundamental widgets in
Android.Here are four notable XML attributes:
1. android:text:
■ Purpose: Sets the actual text content that the TextView will display.
■ Example: android:text="Hello, Android!"
2. android:textSize:
■ Purpose: Defines the size of the text within the TextView. It's recommended
to use sp (scale-independent pixels) for text size to ensure it scales well with
user font preferences.
■ Example: android:textSize="20sp"
3. android:textColor:
■ Purpose: Sets the color of the text. Can be a hexadecimal color code (e.g.,
#FF0000 for red), an Android color resource (e.g., @android:color/black), or a
custom color defined in colors.xml.
■ Example: android:textColor="#00FF00" (green)
4. android:gravity:
■ Purpose: Controls the alignment of the text within the TextView's boundaries.
This is different from layout_gravity which positions the TextView itself within
its parent.
■ Values: Common values include center, left, right, top, bottom, or
combinations like center_horizontal|bottom.
■ Example: android:gravity="center"
11.Explain EditText view with any four notable XML attributes. An EditText is a UI widget
that provides a text input field, allowing users to type and modify text. It is a subclass of
TextView that adds text editing capabilities.Here are four notable XML attributes:
1. android:hint:
■ Purpose: Displays a light-colored hint text in the EditText when it is empty.
This hint disappears once the user starts typing.
■ Example: android:hint="Enter your username"
2. android:inputType:
■ Purpose: Specifies the type of input the EditText is intended for, which helps
the system optimize the soft keyboard layout for that input.
■ Values: text, number, textPassword, phone, textEmailAddress, etc. Can be
combined using |.
■ Example: android:inputType="textPassword"
3. android:singleLine:
■ Purpose: If set to true, forces the EditText to be a single line, preventing line
breaks. This attribute is deprecated in favor of android:maxLines="1".
■ Example: android:singleLine="true" (or android:maxLines="1")
4. android:drawableEnd (or drawableRight):
■ Purpose: Places a drawable (an image) at the end (right side for LTR
layouts) of the EditText text. Useful for icons like a clear button or an eye icon
for password visibility.
■ Example: android:drawableEnd="@drawable/ic_clear"
12.Explain Button view with example XML code snippet to define a Button and
implement listener to handle click event. A Button view is a UI component that triggers
an action when the user taps it.XML Code Snippet:
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true" />
Java Code for Click Event Listener (in an Activity or Fragment):
// Inside your Activity's onCreate method or Fragment's
onCreateView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Assuming your
layout file is activity_main.xml
Button myButton = findViewById(R.id.my_button);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// This code will execute when the button is clicked
Toast.makeText(MainActivity.this, "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});
}
13.Explain RadioButton view with example XML code snippet to define a RadioGroup
with two RadioButton. A RadioButton is a two-state button that can be either checked or
unchecked. When a RadioButton is part of a RadioGroup, only one RadioButton within
that group can be selected at a time, ensuring mutual exclusivity.XML Code Snippet:
<RadioGroup
android:id="@+id/gender_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"> <RadioButton
android:id="@+id/radio_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true" /> <RadioButton
android:id="@+id/radio_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
Java Code to handle selection (in an Activity or Fragment):
// Inside your Activity's onCreate method or Fragment's
onCreateView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup genderRadioGroup =
findViewById(R.id.gender_radio_group);
genderRadioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int
checkedId) {
if (checkedId == R.id.radio_male) {
Toast.makeText(MainActivity.this, "Male selected",
Toast.LENGTH_SHORT).show();
} else if (checkedId == R.id.radio_female) {
Toast.makeText(MainActivity.this, "Female
selected", Toast.LENGTH_SHORT).show();
}
}
});
}
14.Explain CheckBox view with example XML code snippet to define a CheckBox and
implement listener to handle click event. A CheckBox is a two-state button that can be
either checked or unchecked, allowing the user to select multiple options from a set.XML
Code Snippet:
<CheckBox
android:id="@+id/accept_terms_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I accept the terms and conditions"
android:checked="false" /> ```
**Java Code for Click Event Listener (in an Activity or
Fragment):**
```java
// Inside your Activity's onCreate method or Fragment's
onCreateView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CheckBox termsCheckbox =
findViewById(R.id.accept_terms_checkbox);
termsCheckbox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "Terms
accepted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Terms not
accepted", Toast.LENGTH_SHORT).show();
}
}
});
}
15.Explain ToggleButton view with example XML code snippet to define ToggleButton
and implement listener to find its on/off status. A ToggleButton is a two-state button
that visually indicates its current state (ON/OFF). It's useful for settings or features that
can be toggled on or off.XML Code Snippet:
<ToggleButton
android:id="@+id/wifi_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Wi-Fi ON"
android:textOff="Wi-Fi OFF"
android:checked="false" /> ```
**Java Code for Listener (in an Activity or Fragment):**
```java
// Inside your Activity's onCreate method or Fragment's
onCreateView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton wifiToggle = findViewById(R.id.wifi_toggle);
wifiToggle.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
Toast.makeText(MainActivity.this, "Wi-Fi is ON",
Toast.LENGTH_SHORT).show();
// Perform actions when Wi-Fi is turned ON
} else {
Toast.makeText(MainActivity.this, "Wi-Fi is OFF",
Toast.LENGTH_SHORT).show();
// Perform actions when Wi-Fi is turned OFF
}
}
});
}
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dr
opdown_item);
// 3. Set the adapter to the Spinner
countrySpinner.setAdapter(adapter);
// 4. Handle item selection
countrySpinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View
view, int position, long id) {
String selectedCountry =
parent.getItemAtPosition(position).toString();
selectedCountryText.setText("Selected Country: " +
selectedCountry);
Toast.makeText(MainActivity.this, "You selected: "
+ selectedCountry, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing or handle the case where nothing is
selected
}
});
}
}
2. Create a Java Class for the DialogFragment: Extend DialogFragment and
override onCreateView to inflate your custom layout.
■ File:
app/src/main/java/com/example/yourapp/MyCustomDialogFragment.java
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
public class MyCustomDialogFragment extends DialogFragment {
private EditText dialogEditText;
private Button okButton;
// Optional: Interface for communication with the hosting
Activity/Fragment
public interface OnInputListener {
void sendInput(String input);
}
public OnInputListener mOnInputListener;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater
inflater, @Nullable ViewGroup container, @Nullable Bundle
savedInstanceState) {
// Inflate the custom layout for the dialog
View view =
inflater.inflate(R.layout.dialog_my_custom, container,
false);
dialogEditText =
view.findViewById(R.id.dialog_edit_text);
okButton = view.findViewById(R.id.dialog_ok_button);
okButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
String input =
dialogEditText.getText().toString();
if (!input.isEmpty()) {
// Send data back to the
activity/fragment
if (mOnInputListener != null) {
mOnInputListener.sendInput(input);
}
dismiss(); // Close the dialog
} else {
Toast.makeText(getContext(), "Please
enter something", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
// Optional: Override onCreateDialog for more control
over dialog appearance (e.g., AlertDialog.Builder)
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle
savedInstanceState) {
// If you want a basic dialog without a custom
layout,
// or want to wrap your custom view in an AlertDialog
for title/buttons, use this.
// For a completely custom layout as above,
onCreateView is sufficient.
return super.onCreateDialog(savedInstanceState);
}
// This method ensures the hosting activity/fragment
implements the listener
@Override
public void onAttach(@NonNull android.content.Context
context) {
super.onAttach(context);
try {
mOnInputListener = (OnInputListener)
getActivity();
} catch (ClassCastException e) {
throw new
ClassCastException(getActivity().toString()
+ " must implement OnInputListener");
}
}
}
3. Display the DialogFragment from your Activity or another Fragment: You'll
need a FragmentManager to show the DialogFragment.
■ In your MainActivity.java (or hosting Fragment):
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
public class MainActivity extends AppCompatActivity implements
MyCustomDialogFragment.OnInputListener {
private Button showDialogButton;
private TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Your main activity
layout
showDialogButton = findViewById(R.id.show_dialog_button); //
Assuming a button in your main layout
resultTextView = findViewById(R.id.result_text_view); //
Assuming a TextView to display result
showDialogButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
MyCustomDialogFragment dialog = new
MyCustomDialogFragment();
// Use getSupportFragmentManager() for Activities
// Use getChildFragmentManager() for Fragments hosting
other Fragments
dialog.show(getSupportFragmentManager(),
"MyCustomDialogFragment");
}
});
}
@Override
public void sendInput(String input) {
// This method is called when the OK button in the dialog is
clicked
// and data is sent back.
resultTextView.setText("Dialog Input: " + input);
Toast.makeText(this, "Received from dialog: " + input,
Toast.LENGTH_LONG).show();
}
}
(Make sure to add a button with id/show_dialog_button and a TextView with
id/result_text_view in your activity_main.xml for this example to work.)This process
involves creating a dedicated layout for the dialog, a DialogFragment class to manage its
lifecycle and interactions, and then using the FragmentManager to display it. The optional
OnInputListener interface demonstrates a common pattern for communication between the
dialog and its host.