English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PopupWindow d'Android imitant le popup en bas de l'écran iOS

Préambule

Dans l'H5Dans l'époque brûlante, de nombreux cadres ont sorti des contrôles de fenêtre contextuelle en bas de l'écran5Connu sous le nom de menu contextuel ActionSheet, aujourd'hui nous allons imiter une fenêtre contextuelle en bas de l'écran iOS, inspirée de la fonction de sélection de photo de profil de QQ d'Apple.

Texte principal

Pas de temps à perdre, voici l'effet que nous devons réaliser aujourd'hui


Le code complet de l'ouverture de PopupWindow

private void openPopupWindow(View v) {
  //防止重复按按钮
  if (popupWindow != null && popupWindow.isShowing()) {
    return;
  }
  //设置PopupWindow的View
  View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
  popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,
      RelativeLayout.LayoutParams.WRAP_CONTENT);
  //设置背景,这个没什么效果,不添加会报错
  popupWindow.setBackgroundDrawable(new BitmapDrawable());
  //设置点击弹窗外隐藏自身
  popupWindow.setFocusable(true);
  popupWindow.setOutsideTouchable(true);
  //设置动画
  popupWindow.setAnimationStyle(R.style.PopupWindow);
  //设置位置
  popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, navigationHeight);
  //设置消失监听
  popupWindow.setOnDismissListener(this);
  //设置PopupWindow的View点击事件
  setOnPopupViewClick(view);
  //设置背景色
  setBackgroundAlpha(0.5f);
}

Analyse des étapes :

La mise en page de PopupWindow
La création de PopupWindow
PopupWindow ajoute l'effet d'animation
PopupWindow configure l'ombre de fond
PopupWindow écoute les événements de clic
Obtenir la hauteur de la barre de navigation

La mise en page de PopupWindow : dans le Layout, concevoir la mise en page nécessaire

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
  <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:background="@drawable/popup_shape" android:orientation="vertical">
    <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:text="Vous pouvez télécharger les photos sur le mur photo" android:textColor="#666" android:textSize="}}14sp" />
    <View android:layout_width="match_parent" android:layout_height="0.1px" android:background="#888" />
    <TextView android:id="@+id/tv_pick_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:text="Choisir à partir de l'album photo du téléphone" android:textColor="#118" android:textSize="}}18sp" />
    <View android:layout_width="match_parent" android:layout_height="0.1px" android:background="#888" />
    <TextView android:id="@+id/tv_pick_zone" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:text="Choisir à partir de l'album photo de l'espace" android:textColor="#118" android:textSize="}}18sp" />
  </LinearLayout>
  <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:background="@drawable/popup_shape">
    <TextView android:id="@+id/tv_cancel" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:text="Annuler" android:textColor="#118" android:textSize="}}18sp" android:textStyle="bold" />
  </LinearLayout>
</LinearLayout>

Son effet est :


Création de PopupWindow : cette création est la même que pour la création de nos contrôles ordinaires

//设置PopupWindow的View
View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);

Ajouter des effets d'animation à PopupWindow : nous créons un dossier anim, créons nos animations de sortie et d'entrée, puis ajoutons nos animations dans le style

<?xml version="1.0" encoding="utf-8"?>
!--Animation d'entrée-->
<translate xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" android:fromYDelta="100%" android:toYDelta="0" android:duration="200"/>
<?xml version="1.0" encoding="utf-8"?>
!--Animation de sortie-->
<translate xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" android:fromYDelta="0" android:toYDelta="100%" android:duration="200"/>
!--Animation de fenêtre pop-up-->
<style name="PopupWindow"> <item name="android:windowEnterAnimation">@anim/window_in</item> <item name="android:windowExitAnimation">@anim/window_out</item> </style>

//设置动画
popupWindow.setAnimationStyle(R.style.PopupWindow);

Définir l'ombre de fond de PopupWindow : définir l'opacité à 0 lors de l'ouverture de la fenêtre pop-up5, définir l'opacité à1

//Définir l'effet de transparence d'arrière-plan de l'écran
public void setBackgroundAlpha(float alpha) {
  WindowManager.LayoutParams lp = getWindow().getAttributes();
  lp.alpha = alpha;
  getWindow().setAttributes(lp);
}

PopupWindow écoute les événements de clic : écouter les événements de clic des composants à l'intérieur de notre PopupWindow

//设置PopupWindow的View点击事件
setOnPopupViewClick(view);
private void setOnPopupViewClick(View view) {
  TextView tv_pick_phone, tv_pick_zone, tv_cancel;
  tv_pick_phone = (TextView) view.findViewById(R.id.tv_pick_phone);
  tv_pick_zone = (TextView) view.findViewById(R.id.tv_pick_zone);
  tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
  tv_pick_phone.setOnClickListener(this);
  tv_pick_zone.setOnClickListener(this);
  tv_cancel.setOnClickListener(this);
}

Obtenir la hauteur de NavigationBar : ici, il faut adapter le fait que certains téléphones n'ont pas de NavigationBar et d'autres en ont. Ici, nous démontrons avec la présence de NavigationBar
int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
navigationHeight = getResources().getDimensionPixelSize(resourceId);

Pour les téléphones avec NavigationBar, définir la position d'apparition de PopupWindow
//设置位置
popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, navigationHeight);

Pour les téléphones sans NavigationBar, définir la position d'apparition de PopupWindow
//设置位置
popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

Code source

Github :https://github.com/AndroidHensen/IOSPopupWindow

public class MainActivity extends AppCompatActivity implements View.OnClickListener, PopupWindow.OnDismissListener {
  private Button bt_open;
  private PopupWindow popupWindow;
  private int navigationHeight;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt_open = (Button) findViewById(R.id.bt_open);
    bt_open.setOnClickListener(this);
    int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
    navigationHeight = getResources().getDimensionPixelSize(resourceId);
  }
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.bt_open:
        openPopupWindow(v);
        break;
      case R.id.tv_pick_phone:
        Toast.makeText(this, "Sélectionner à partir de l'album photo du téléphone", Toast.LENGTH_SHORT).show();
        popupWindow.dismiss();
        break;
      case R.id.tv_pick_zone:
        Toast.makeText(this, "Sélectionner à partir de l'album photo de l'espace", Toast.LENGTH_SHORT).show();
        popupWindow.dismiss();
        break;
      case R.id.tv_cancel:
        popupWindow.dismiss();
        break;
    }
  }
  private void openPopupWindow(View v) {
    //防止重复按按钮
    if (popupWindow != null && popupWindow.isShowing()) {
      return;
    }
    //设置PopupWindow的View
    View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
    popupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
    //设置背景,这个没什么效果,不添加会报错
    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    //设置点击弹窗外隐藏自身
    popupWindow.setFocusable(true);
    popupWindow.setOutsideTouchable(true);
    //设置动画
    popupWindow.setAnimationStyle(R.style.PopupWindow);
    //设置位置
    popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, navigationHeight);
    //设置消失监听
    popupWindow.setOnDismissListener(this);
    //设置PopupWindow的View点击事件
    setOnPopupViewClick(view);
    //设置背景色
    setBackgroundAlpha(0.5f);
  }
  private void setOnPopupViewClick(View view) {
    TextView tv_pick_phone, tv_pick_zone, tv_cancel;
    tv_pick_phone = (TextView) view.findViewById(R.id.tv_pick_phone);
    tv_pick_zone = (TextView) view.findViewById(R.id.tv_pick_zone);
    tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
    tv_pick_phone.setOnClickListener(this);
    tv_pick_zone.setOnClickListener(this);
    tv_cancel.setOnClickListener(this);
  }
  //Définir l'effet de transparence d'arrière-plan de l'écran
  public void setBackgroundAlpha(float alpha) {
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.alpha = alpha;
    getWindow().setAttributes(lp);
  }
  @Override
  public void onDismiss() {
    setBackgroundAlpha(1);
  }
}

Voici la fin de cet article, j'espère que cela pourra aider à votre apprentissage, et j'espère que vous serez nombreux à soutenir le tutoriel d'alarme.

Déclaration : le contenu de cet article est issu d'Internet, propriété de ses auteurs respectifs. Le contenu est contribué et téléchargé par les utilisateurs d'Internet de manière volontaire. Ce site n'est pas propriétaire des droits d'auteur, n'a pas fait l'objet d'une rédaction humaine et n'assume aucune responsabilité juridique connexe. Si vous trouvez du contenu suspect de violation de droits d'auteur, veuillez envoyer un e-mail à : notice#oldtoolbag.com (veuillez remplacer # par @ lors de l'envoi d'un e-mail pour signaler une violation, et fournir des preuves pertinentes. Une fois vérifié, ce site supprimera immédiatement le contenu suspect de violation de droits d'auteur.)

Vous pourriez aussi aimer