To create a popup window in Android using Java, you can use the PopupWindow
class.
Here is an example of how you can create a PopupWindow
and display it in an Android activity:
import android.widget.PopupWindow; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a PopupWindow PopupWindow popupWindow = new PopupWindow(this); // Set the content view of the PopupWindow popupWindow.setContentView(R.layout.popup_window); // Set the width and height of the PopupWindow popupWindow.setWidth(600); popupWindow.setHeight(400); // Show the PopupWindow popupWindow.showAtLocation(findViewById(R.id.root), Gravity.CENTER, 0, 0); } }
This code creates a new PopupWindow
object called popupWindow
and sets its content view to a layout file called popup_window.xml
. It then sets the width and height of the PopupWindow
using the setWidth
and setHeight
methods.
Finally, the PopupWindow
is displayed using the showAtLocation
method, which takes a view to anchor the PopupWindow
, and the gravity and x and y offset values. In this example, the PopupWindow
is anchored to the root view of the activity and is displayed at the center of the screen.
You can also use the android.support.v7.widget.AppCompatPopupWindow
class to create a PopupWindow
if you are using the Android Support Library.
import android.support.v7.widget.AppCompatPopupWindow; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create a PopupWindow AppCompatPopupWindow popupWindow = new AppCompatPopupWindow(this); // Set the content view of the PopupWindow popupWindow.setContentView(R.layout.popup_window); // Set the width and height of the PopupWindow popupWindow.setWidth(600); popupWindow.setHeight(400); // Show the PopupWindow popupWindow.showAtLocation(findViewById(R.id.root), Gravity.CENTER, 0, 0); } }
This code is similar to the previous example, but it uses the AppCompatPopupWindow
class instead of the PopupWindow
class. The AppCompatPopupWindow
class is a backport of the PopupWindow
class for use with the Android Support Library.