Android Popup Window Example


Displaying a Popup Window




Today we will learn how to display a Popup window in your android application user interface. A popup window is used to display an arbitrary view that can hold your specified widgets and texts. Android Popup window is a floating container and it appears on top of the current activity. We can populate a Popup window by using android SDK’s PopupWindow class. This class has many useful methods. Those will help us to generate a beautiful Popup window.




Ok, now let’s describe our code snippets. How do we display a Popup window in our android application? First, we create an activity XML file and put a Button widget. That button click event performs the essential task to generate a Popup window on top of the current activity.




We create another XML custom layout file that holds the widgets of the Popup window. Simply put an ImageButton and a TextView widget on it. The image button is used to show a close button to dismiss the Popup window and the text widget display a simple message. In this custom layout file, we used a RelativeLayout to wrap the widget.




Now, let’s describe the actual coding on the Java file. On the button click event, we generate and display the Popup window on top of the current activity. We inflate the custom XML layout file using layout inflater. Then we used this custom layout to generate a new PopupWindow class instance. Next, we set an elevation of the Popup window, so that it will get a material design look.




Third, we define the Popup window close/dismiss button. To do this we choose the custom layout’s image button. On the image button click event, we call the dismiss method to close the Popup window. Finally, we specify the activity location where we want to show our newly created Popup window. Here we display the Popup window at the center position of the current activity. The following code snippets and output images will help you to understand the full sense more efficiently.





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity"
android:background="#f5f1e0"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup Window"
/>
</RelativeLayout>






res/layout/custom_layout.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:background="#ab2fc4"
>
<ImageButton
android:id="@+id/ib_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_close_white_24dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:background="@null"
/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a sample popup window."
android:layout_centerInParent="true"
android:padding="25sp"
/>
</RelativeLayout>



MainActivity.java



package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.view.ViewGroup.LayoutParams;


public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;

private RelativeLayout mRelativeLayout;
private Button mButton;

private PopupWindow mPopupWindow;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

// Get the activity
mActivity = MainActivity.this;

// Get the widgets reference from XML layout
mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
mButton = (Button) findViewById(R.id.btn);

// Set a click listener for the text view
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initialize a new instance of LayoutInflater service
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);

// Inflate the custom layout/view
View customView = inflater.inflate(R.layout.custom_layout,null);

/*
public PopupWindow (View contentView, int width, int height)
Create a new non focusable popup window which can display the contentView.
The dimension of the window must be passed to this constructor.

The popup does not provide any background. This should be handled by
the content view.

Parameters
contentView : the popup's content
width : the popup's width
height : the popup's height
*/
// Initialize a new instance of popup window
mPopupWindow = new PopupWindow(
customView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);

// Set an elevation value for popup window
// Call requires API level 21
if(Build.VERSION.SDK_INT>=21){
mPopupWindow.setElevation(5.0f);
}

// Get a reference for the custom view close button
ImageButton closeButton = (ImageButton) customView.findViewById(R.id.ib_close);

// Set a click listener for the popup window close button
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Dismiss the popup window
mPopupWindow.dismiss();
}
});

/*
public void showAtLocation (View parent, int gravity, int x, int y)
Display the content view in a popup window at the specified location. If the
popup window cannot fit on screen, it will be clipped.
Learn WindowManager.LayoutParams for more information on how gravity and the x
and y parameters are related. Specifying a gravity of NO_GRAVITY is similar
to specifying Gravity.LEFT | Gravity.TOP.

Parameters
parent : a parent view to get the getWindowToken() token from
gravity : the gravity which controls the placement of the popup window
x : the popup's x location offset
y : the popup's y location offset
*/
// Finally, show the popup window at the center location of root relative layout
mPopupWindow.showAtLocation(mRelativeLayout, Gravity.CENTER,0,0);
}
});
}
}








Android Popup Menu Example








MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.PopupMenu;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private Context mContext;
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the context
mContext = this;

// Get the widgets reference from XML layout
mTextView = findViewById(R.id.textView);

// Set a click listener for the text view
mTextView.setOnClickListener(view -> {
showPopupMenu();
});
}



// Method to show a popup menu
private void showPopupMenu(){
// Initialize a new instance of popup menu
PopupMenu popupMenu = new PopupMenu(mContext,mTextView);

// Inflate the popup menu
popupMenu.getMenuInflater().inflate(
R.menu.textview_popup_menu,popupMenu.getMenu());


// Set a click listener for menu item click
popupMenu.setOnMenuItemClickListener(menuItem -> {
int id = menuItem.getItemId();

if (id == R.id.red){
// Set the text color to red
mTextView.setTextColor(Color.RED);
return true;
}else if (id == R.id.green){
// Set the text color to green
mTextView.setTextColor(Color.GREEN);
return true;
}else if (id == R.id.blue){
// Set the text color to blue
mTextView.setTextColor(Color.BLUE);
return true;
}else {
return false;
}
});


// Finally, show the popup menu
popupMenu.show();
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:text="Click Me To Open A Popup Menu."
android:textSize="50sp"
android:textStyle="italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>





res/menu/textview_popup_menu.xml



<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/red"
android:title="Red"
android:icon="@drawable/ic_action_palette" />
<item
android:id="@+id/green"
android:title="Green"
android:icon="@drawable/ic_action_palette" />
<item
android:id="@+id/blue"
android:title="Blue"
android:icon="@drawable/ic_action_palette" />
</menu>











android - Add, update and remove Menu item programmatically








MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
mTextView = findViewById(R.id.textView);
}


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


@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
String title = item.getTitle().toString();

if (id == R.id.delete) {
mTextView.append("\n" + title + " Clicked.");
return true;
} else if (id == R.id.copy) {
mTextView.append("\n" + title + " Clicked.");
return true;
} else if (id == R.id.paste) {
mTextView.append("\n" + title + " Clicked.");
return true;
}else {
return super.onOptionsItemSelected(item);
}
}



@Override
public boolean onPrepareOptionsMenu(Menu menu){
// Add new Menu Item
// Specify an id for the new menu item
int purpleId = 101;

// Check the menu item already added or not
if(menu.findItem(purpleId) == null){
// If it not exists then add the menu item to menu
MenuItem cut = menu.add(
Menu.NONE, // groupId
purpleId, // itemId
2, // order
"Cut" // title
);

// Set an icon for the new menu item
cut.setIcon(R.drawable.ic_action_content_cut);

// Set the show as action flags for new menu item
cut.setShowAsActionFlags(
MenuItem.SHOW_AS_ACTION_WITH_TEXT |
MenuItem.SHOW_AS_ACTION_ALWAYS
);

// Set a click listener for the new menu item
cut.setOnMenuItemClickListener(menuItem -> {
mTextView.append("\n" + cut.getTitle() + " Clicked.");
return true;
});

mTextView.append("\nCut MenuItem Added.");
}


// Remove a menu item from menu
if(menu.findItem(R.id.copy)!=null){
// If copy menu item is not deleted then
// delete/remove it from the menu
menu.removeItem(R.id.copy);
mTextView.append("\nCopy MenuItem Deleted.");
}


// Update/modify/change a menu item
MenuItem paste = menu.findItem(R.id.paste);
if(paste.getTitle() != "Paste Text"){
// If paste menu item title not updated
// then update/change it
paste.setTitle("Paste Text");
mTextView.append("\nPaste MenuItem Edited.");
}


super.onPrepareOptionsMenu(menu);
return true;
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tool="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tool:text="TextView"
android:fontFamily="sans-serif"
android:textSize="26sp"
android:textStyle="italic"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>






res/menu/toolbar_options_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/delete"
android:title="Delete"
android:icon="@drawable/ic_action_delete"
app:showAsAction="always|withText"
android:orderInCategory="1" />
<item
android:id="@+id/copy"
android:title="Copy"
android:icon="@drawable/ic_action_content_copy"
app:showAsAction="ifRoom|withText"
android:orderInCategory="2" />
<item
android:id="@+id/paste"
android:title="Paste"
android:icon="@drawable/ic_action_content_paste"
app:showAsAction="ifRoom|withText"
android:orderInCategory="3" />
</menu>









android - How to group Menu items








MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
mTextView = findViewById(R.id.textView);
}


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


@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
String title = item.getTitle().toString();

if (id == R.id.text_bold){
mTextView.append("\n" + title + " Clicked");
return true;
}else if (id == R.id.text_italic){
mTextView.append("\n" + title + " Clicked");
return true;
}else {
return super.onOptionsItemSelected(item);
}
}


// To handle menu text color group items click event
public void onColorGroupItemClick(MenuItem item){
int id = item.getItemId();
String title = item.getTitle().toString();

if(id == R.id.red){
// Checked the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}else if (id == R.id.green){
// Checked the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}else if (id == R.id.blue){
// Checked the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}

}


// To handle menu text size group items click event
public void onSizeGroupItemClick(MenuItem item){
int id = item.getItemId();
String title = item.getTitle().toString();

if(id == R.id.large_text){
// Check the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}else if (id == R.id.medium_text){
// Check the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}else if (id == R.id.small_text){
// Check the item
item.setChecked(true);
mTextView.append("\n" + title + " Checked");
}
}
}






activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tool="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tool:text="TextView"
android:fontFamily="sans-serif"
android:textSize="26sp"
android:textStyle="italic"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>







res/menu/toolbar_options_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" >

<!-- complex menu item to set text style -->
<item
android:id="@+id/text_style"
android:title="Text Style"
app:showAsAction="always|withText"
android:icon="@drawable/ic_action_text_format"
android:orderInCategory="1" >

<!-- text style menu's sub menu start from here -->
<menu>
<!-- first group (text color) of text style sub menu -->
<group
android:id="@+id/text_color_group"
android:checkableBehavior="single" >
<!-- text color group's items -->
<item
android:title="Select Text Color"
android:enabled="false"
android:checkable="false" />
<item
android:id="@+id/red"
android:title="Red"
android:icon="@drawable/ic_action_palette"
android:onClick="onColorGroupItemClick" />
<item
android:id="@+id/green"
android:title="Green"
android:icon="@drawable/ic_action_palette"
android:onClick="onColorGroupItemClick" />
<item
android:id="@+id/blue"
android:title="Blue"
android:icon="@drawable/ic_action_palette"
android:onClick="onColorGroupItemClick" />
</group>

<!-- second group (text size) of text style sub menu -->
<group
android:id="@+id/text_size_group"
android:checkableBehavior="single" >
<!-- text size group's items -->
<item
android:title="Select Text Size"
android:enabled="false"
android:checkable="false" />
<item
android:id="@+id/large_text"
android:title="Large"
android:icon="@drawable/ic_action_text_fields"
android:onClick="onSizeGroupItemClick" />
<item
android:id="@+id/medium_text"
android:title="Medium"
android:icon="@drawable/ic_action_text_fields"
android:onClick="onSizeGroupItemClick" />
<item
android:id="@+id/small_text"
android:title="Small"
android:icon="@drawable/ic_action_text_fields"
android:onClick="onSizeGroupItemClick" />
</group>
</menu>
</item>

<!-- bold text menu item -->
<item
android:id="@+id/text_bold"
android:title="Bold Text"
app:showAsAction="always|withText"
android:icon="@drawable/ic_action_format_bold"
android:orderInCategory="2" />
<!-- italic text menu item -->
<item
android:id="@+id/text_italic"
android:title="Italic Text"
app:showAsAction="never|withText"
android:icon="@drawable/ic_action_format_italic"
android:orderInCategory="3" />
</menu>












Android SubMenu Example








MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
mTextView = findViewById(R.id.textView);
}


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


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

if (id == R.id.red){
// Set the text color to red
mTextView.setTextColor(Color.RED);
return true;
}else if(id == R.id.green){
// Set the text color to green
mTextView.setTextColor(Color.GREEN);
return true;
}else if (id == R.id.blue){
// Set the text color to blue
mTextView.setTextColor(Color.BLUE);
return true;
}else if (id == R.id.large_text){
// Set the text size to large
mTextView.setTextSize(
TypedValue.COMPLEX_UNIT_SP, 50);
return true;
}else if (id == R.id.medium_text){
// Set the text size to medium
mTextView.setTextSize(
TypedValue.COMPLEX_UNIT_SP, 35);
return true;
}else if (id == R.id.small_text){
// Set the text size to small
mTextView.setTextSize(
TypedValue.COMPLEX_UNIT_SP, 25);
return true;
}else {
return super.onOptionsItemSelected(item);
}
}
}





activity_main.xml




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:text="I am a TextView"
android:textSize="26sp"
android:textStyle="italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>





res/menu/toolbar_options_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/text_color"
android:title="Text Color"
app:showAsAction="always|withText"
android:icon="@drawable/ic_action_text_format"
android:orderInCategory="1">

<!-- Starting sub menu which have three items-->
<menu>
<item
android:id="@+id/red"
android:title="Red"
android:icon="@drawable/ic_action_palette" />
<item
android:id="@+id/green"
android:title="Green"
android:icon="@drawable/ic_action_palette" />
<item
android:id="@+id/blue"
android:title="Blue"
android:icon="@drawable/ic_action_palette" />
</menu>
</item>

<item
android:id="@+id/large_text"
android:title="Large Text"
app:showAsAction="ifRoom|withText"
android:orderInCategory="2"
android:icon="@drawable/ic_action_text_fields" />
<item
android:id="@+id/medium_text"
android:title="Medium Text"
app:showAsAction="ifRoom|withText"
android:orderInCategory="3"
android:icon="@drawable/ic_action_text_fields" />
<item
android:id="@+id/small_text"
android:title="Small Text"
app:showAsAction="ifRoom|withText"
android:orderInCategory="4"
android:icon="@drawable/ic_action_text_fields" />
</menu>











android - How to use CheckBox in Options Menu








MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private boolean mIsBold = false;
private boolean mIsItalic = false;
private boolean mIsUnderlined = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
mTextView = findViewById(R.id.textView);

// Update textView
updateTextView();
}


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



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

if (id == R.id.blue){
mTextView.setTextColor(Color.BLUE);
updateTextView();
return true;
}else if (id == R.id.bold){
// Toggle item is checked state
item.setChecked(!item.isChecked());
mIsBold = item.isChecked();
updateTextView();
return true;
}else if (id == R.id.italic){
item.setChecked(!item.isChecked());
mIsItalic = item.isChecked();
updateTextView();
return true;
}else if (id == R.id.underline){
item.setChecked(!item.isChecked());
mIsUnderlined = item.isChecked();
updateTextView();
return true;
}else {
return super.onOptionsItemSelected(item);
}
}



// Method to update text view text
private void updateTextView(){
mTextView.setText(
"Bold Text Checked ?: " + mIsBold
+ "\n\nItalic Text Checked ?: " + mIsItalic
+ "\n\nUnderlined Text Checked ?: "
+ mIsUnderlined
);
}
}






activity_main.xml




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
android:textStyle="italic"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>





res/menu/toolbar_options_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/blue"
android:title="Blue"
android:icon="@drawable/ic_action_palette"
app:showAsAction="always|withText"
android:orderInCategory="1"
/>
<item
android:id="@+id/bold"
android:title="Bold Text"
app:showAsAction="never"
android:orderInCategory="2"
android:checkable="true"
/>
<item
android:id="@+id/italic"
android:title="Italic Text"
app:showAsAction="never"
android:orderInCategory="3"
android:checkable="true"
/>
<item
android:id="@+id/underline"
android:title="Underlined Text"
app:showAsAction="never"
android:orderInCategory="4"
android:checkable="true"
/>
</menu>











android - How to enable WebView zoom









MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private WebView mWebView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
mWebView = findViewById(R.id.webView);

// Request to render the web page
renderWebPage("https://www.google.com");
}



// Custom method to render a web page
protected void renderWebPage(String urlToRender){
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
// Do something on page loading started
}

@Override
public void onPageFinished(WebView view, String url) {
// Do something when page loading finished
}
});

mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(
WebView view, int newProgress) {
}
});


// Enable the javascript
mWebView.getSettings().setJavaScriptEnabled(true);


// Enable zoom
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(true);


// Render the web page
mWebView.loadUrl(urlToRender);
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC">

<WebView
android:id="@+id/webView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>






android - Display ProgressBar while loading in WebView









MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
private MainActivity mContext;
private WebView mWebView;
private ProgressBar mProgressBar;
private Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the activity
mContext = MainActivity.this;

// Get the widgets reference from XML layout
mButton = findViewById(R.id.button);
mWebView = findViewById(R.id.webView);
mProgressBar = findViewById(R.id.progressBar);


// Set a click listener for button widget
mButton.setOnClickListener(view -> {
// Request to render the web page
renderWebPage("https://www.android--code.com/");
});
}



// Custom method to render a web page
protected void renderWebPage(String urlToRender){
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon){
// Do something on page loading started
// Visible the progressbar
mProgressBar.setVisibility(View.VISIBLE);
}

@Override
public void onPageFinished(WebView view, String url){
// Do something when page loading finished
showToast("Page loaded");
}

});


mWebView.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(
WebView view, int newProgress){
// Update the progress bar
// with page loading progress
mProgressBar.setProgress(newProgress);

// Show the progress
mButton.setText(
"URL Loaded " + newProgress + "%");

if(newProgress == 100){
// Hide the progressbar
mProgressBar.setVisibility(View.GONE);
mButton.setText("Load URL");
}
}
});


// Enable the javascript
mWebView.getSettings().setJavaScriptEnabled(true);

// Render the web page
mWebView.loadUrl(urlToRender);
}



// Method to show toast message
private void showToast(String message){
Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="Load URL"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ProgressBar
android:id="@+id/progressBar"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<WebView
android:id="@+id/webView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>









android - How to get WebView loaded page title and url









MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Objects;


public class MainActivity extends AppCompatActivity {
private MainActivity mContext;
private WebView mWebView;
private String mTitle = "";
private String mUrl = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the activity
mContext = MainActivity.this;

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
mWebView = findViewById(R.id.webView);


// Set a click listener for button widget
button.setOnClickListener(view -> {
// Request to render the web page
renderWebPage("https://www.android--code.com/?m=1");
});
}



// Custom method to render a web page
protected void renderWebPage(String urlToRender){
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(
WebView view, String url, Bitmap favicon){
// Do something on page loading started
showToast("Page loading started");

// Only url is available in this stage
mUrl = view.getUrl();

// Update the action bar
Objects.requireNonNull(getSupportActionBar())
.setSubtitle(mUrl);
}

@Override
public void onPageFinished(WebView view, String url){
// Do something when page loading finished
showToast("Page loaded");

// Url and title are available at this stage
mUrl = view.getUrl();
mTitle = view.getTitle();

// Update the action bar
Objects.requireNonNull(getSupportActionBar())
.setTitle(mTitle);
getSupportActionBar().setSubtitle(mUrl);
}

});


// Enable the javascript
mWebView.getSettings().setJavaScriptEnabled(true);

// Render the web page
mWebView.loadUrl(urlToRender);
}



// Method to show toast message
private void showToast(String message){
Toast.makeText(mContext,message,Toast.LENGTH_SHORT).show();
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="Load URL"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<WebView
android:id="@+id/webView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>