Всплывающее окно Android не заполняет размер экрана?
Я пытаюсь создать простое всплывающее окно. Но каждый раз, когда я делаю это, он заканчивается очень маленьким... и не той длиной, которую я хочу. Вот как выглядит всплывающее окно:
![введите описание изображения здесь]()
Вот мой макет для всплывающего окна:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_element"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#444444"
android:padding="10px"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Transfering data"
android:textColor="@color/white"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Status"
android:textColor="@color/white"/>
<TextView android:id="@+id/server_status_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Awaiting answer..."
android:paddingLeft="10sp"
android:textColor="@color/white"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:gravity="center_horizontal|bottom">
<Button android:id="@+id/end_data_send_button"
android:layout_width="100dp"
android:layout_height="100dp"
android:drawablePadding="3sp"
android:layout_centerHorizontal="true"
android:text="Cancel" />
</LinearLayout>
</LinearLayout>
Вот мой код Java:
private PopupWindow pw;
private void bindActivity() {
fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB);
fabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initiatePopupWindow();
}
});
}
private void initiatePopupWindow() {
try {
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) ProfileView.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
// create a 300px width and 470px height PopupWindow
pw = new PopupWindow(layout, 300, 470, true);
// display the popup in the center
pw.showAtLocation(layout, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
private View.OnClickListener cancel_button_click_listener = new View.OnClickListener() {
public void onClick(View v) {
pw.dismiss();
}
};
Не могу понять, почему он не работает...
Как получить размер, который я хочу?
Ответы
Ответ 1
Здесь вы не можете использовать макет, который находится в вашем всплывающем окне xml. Вы должны использовать любой вид из основного макета. Прямо сейчас я использую FloatingButton как View для showAtLocation.
fabButton = (ImageButton) findViewById(R.id.activity_profileView_FAB);
fabButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
initiatePopupWindow(v);
}
});
private void initiatePopupWindow(View v) {
try {
//We need to get the instance of the LayoutInflater, use the context of this activity
LayoutInflater inflater = (LayoutInflater) ProfileView.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate the view from a predefined XML layout
View layout = inflater.inflate(R.layout.popup,
(ViewGroup) findViewById(R.id.popup_element));
// create a 300px width and 470px height PopupWindow
pw = new PopupWindow(layout, 300, 470, true);
// display the popup in the center
pw.showAtLocation(v, Gravity.CENTER, 0, 0);
TextView mResultText = (TextView) layout.findViewById(R.id.server_status_text);
Button cancelButton = (Button) layout.findViewById(R.id.end_data_send_button);
cancelButton.setOnClickListener(cancel_button_click_listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Ответ 2
Как сделать простое всплывающее окно Android
Это более полный пример. Это дополнительный ответ, который касается названия вопроса и не обязательно конкретных деталей проблемы ОП. Он будет выглядеть следующим образом.
![введите описание изображения здесь]()
Сделать макет для всплывающего окна
Добавьте файл макета в res/layout
, который определяет, как будет выглядеть всплывающее окно.
popup_window.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#62def8">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:textSize="22sp"
android:text="This is a popup window."/>
</RelativeLayout>
Нажать и показать всплывающее окно
Вот код основной деятельности нашего примера. Всякий раз, когда нажимается кнопка, всплывающее окно раздувается и отображается над активностью. Прикосновение в любом месте экрана отклоняет всплывающее окно.
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonShowPopupWindowClick(View view) {
// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout)
findViewById(R.id.activity_main_layout);
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)
getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = inflater.inflate(R.layout.popup_window, null);
// create the popup window
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
boolean focusable = true; // lets taps outside the popup also dismiss it
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, focusable);
// show the popup window
popupWindow.showAtLocation(mainLayout, Gravity.CENTER, 0, 0);
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
}
}
Для справки, здесь также находится основной макет.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.popupwindow.MainActivity">
<Button
android:text="Show popup window"
android:onClick="onButtonShowPopupWindowClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
</LinearLayout>
Дальнейшее изучение
Это также помогло узнать, как создать всплывающее окно:
Ответ 3
Просто измените
pw = new PopupWindow(layout, 300, 470, true);
чтобы это понравилось
pw = new PopupWindow(layout, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT, true);
и если вам нужны поля на любой стороне, сделайте это в всплывающем xml файле. Также в xml используйте android: layout_height = "wrap_content". Преимуществом этого является то, что он будет выглядеть так же (если вы поместите маржу) на любой экран устройства.