Я делаю приложение для Android, и в некоторых действиях я заставляю приложение отображать всплывающее меню при нажатии некоторых элементов.
Проблема в том, что PopupMenu не отображает все параметры сразу, вместо этого мне придется прокрутить PopupMenu вниз, чтобы увидеть остальные параметры меню.
Эта проблема возникает в двух действиях, но в третьем действии она отображается так, как я хочу, хотя я использую один и тот же код для создания PopupMenu во всех этих трех действиях!
эти две фотографии проясняют проблему, с которой я сталкиваюсь:введите описание изображения здесьвведите описание изображения здесь
и это фотография активности, которая показывает меню, как и ожидалось:введите описание изображения здесь
это код одного из двух действий, которые имеют проблему:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupMenu;
import com.example.android.grad_qurantutor.data.DatabaseHelper;
import java.util.ArrayList;
public class FavoritesActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.general_list);
dbHelper = new DatabaseHelper(this);
final ArrayList<Ayah> arr = dbHelper.getFavorites();
if (arr.size() > 0) {
final AyahAdapter itemsAdapter = new AyahAdapter(this, arr);
final ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Ayah a = arr.get(i);
PopupMenu popup = new PopupMenu(FavoritesActivity.this, listView);
popup.getMenuInflater().inflate(R.menu.menu_favorites_options, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// Respond to a click on the "Add to Favorites" menu option
case R.id.unfavorite:
dbHelper.unfavorite(a.getId());
ArrayList<Ayah> arr = dbHelper.getFavorites();
itemsAdapter.clear();
itemsAdapter.addAll(arr);
itemsAdapter.notifyDataSetChanged();
return true;
case R.id.go_to_surah:
Surah surah = dbHelper.getSurah(a.getSurahId());
Intent myIntent = new Intent(FavoritesActivity.this, AyahsActivity.class);
myIntent.putExtra("surahObj", surah);
myIntent.putExtra("ayahNum", a.getNumber());
startActivity(myIntent);
return true;
case R.id.share_ayah:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBody = a.getText();
shareIntent.putExtra(Intent.EXTRA_TEXT , shareBody);
startActivity(Intent.createChooser(shareIntent , "Share Using"));
return true;
}
return true;
}
});
popup.show();
}
});
}
}
}
А ТАКЖЕ это меню xml:
<menu xmlns:android = "http://schemas.android.com/apk/res/android">
<item
android:id = "@+id/unfavorite"
android:title = "Unfavorite" />
<item
android:id = "@+id/go_to_surah"
android:title = "Go to the Surah" />
<item
android:id = "@+id/share_ayah"
android:title = "Share" />
</menu>
А ТАКЖЕ это макет xml для активности:
<ListView xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:id = "@+id/list"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:background = "#FFF8E1"
android:drawSelectorOnTop = "true"
android:orientation = "vertical" />
и вот коды действий, которые правильно отображают меню, как и ожидалось:
активность:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import com.example.android.grad_qurantutor.data.DatabaseHelper;
import java.util.ArrayList;
public class SearchActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
class Listener implements AdapterView.OnItemClickListener{
private ArrayList<Ayah> arr;
private ListView listView;
public Listener(ArrayList<Ayah> arr, ListView listView){
this.arr = arr;
this.listView = listView;
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final Ayah a = arr.get(i);
PopupMenu popup = new PopupMenu(SearchActivity.this, listView);
popup.getMenuInflater().inflate(R.menu.menu_searched_ayahs_options, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// Respond to a click on the "Add to Favorites" menu option
case R.id.add_favorite2:
dbHelper.addFavoriteAyah(a.getId());
return true;
case R.id.go_to_surah2:
Surah surah = dbHelper.getSurah(a.getSurahId());
Intent myIntent = new Intent(SearchActivity.this, AyahsActivity.class);
myIntent.putExtra("surahObj", surah);
myIntent.putExtra("ayahNum", a.getNumber());
startActivity(myIntent);
return true;
case R.id.share_ayah:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareBody = a.getText();
shareIntent.putExtra(Intent.EXTRA_TEXT , shareBody);
startActivity(Intent.createChooser(shareIntent , "Share Using"));
return true;
}
return true;
}
});
popup.show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
public void search(View view){
dbHelper = new DatabaseHelper(this);
EditText editText = (EditText) findViewById(R.id.search_edit_text);
ArrayList<Ayah> arr = dbHelper.search(editText.getText().toString().trim());
if (arr.size() > 0) {
AyahAdapter itemsAdapter = new AyahAdapter(this, arr);
ListView listView = (ListView) findViewById(R.id.search_list);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new Listener(arr, listView));
}
}
}
А ТАКЖЕ это меню xml:
<menu xmlns:android = "http://schemas.android.com/apk/res/android">
<item
android:id = "@+id/add_favorite2"
android:title = "Add to Favorites" />
<item
android:id = "@+id/go_to_surah2"
android:title = "Go to the Surah" />
<item
android:id = "@+id/share_ayah"
android:title = "Share" />
</menu>
А ТАКЖЕ это макет xml для действия:
<LinearLayout 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 = "#FFF8E1"
android:orientation = "vertical"
tools:context = ".SearchActivity">
<EditText
android:id = "@+id/search_edit_text"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginLeft = "24dp"
android:layout_marginTop = "24dp"
android:layout_marginRight = "24dp"
android:layout_marginBottom = "12dp"
android:hint = "search" />
<Button
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center_horizontal"
android:layout_marginBottom = "24dp"
android:onClick = "search"
android:text = "Search" />
<ListView
android:id = "@+id/search_list"
android:layout_width = "match_parent"
android:layout_height = "0dp"
android:layout_weight = "1"
android:background = "#FFF8E1"
android:drawSelectorOnTop = "true"
android:orientation = "vertical" />
</LinearLayout>




Вы можете использовать popup.setHeight(), чтобы установить желаемую высоту.
Вы также можете использовать popup.showAsDropdown(), чтобы получить больше контроля над тем, где появляется всплывающее окно. Например, я хотел, чтобы мой отображался в определенной позиции относительно enterPhoneNumberButton:
int xOffset = popupWidthInDP > enterPhoneNumberButton.getWidth() ? 0 : enterPhoneNumberButton.getWidth() / 2 - dpToPx(popupWidthInDP / 2);
popup.showAsDropDown(enterPhoneNumberButton, xOffset, -enterPhoneNumberButton.getHeight() - dpToPx(popupHeightInDP));
Преобразование dp в px — обычная задача Android, для которой я создал служебный метод: stackoverflow.com/questions/4605527/преобразование пикселей в dp
Нет таких методов!