PopupWindow 的实现

PopupWindow的实现方式

 

Android的对话框常用的有两种:PopupWindowAlertDialogPopupWindow顾名思义为弹出菜单,不同于AlertDialog对话框,PopupWindow弹出的位置可以很多变化,按照有无偏移分,可以分为无偏移和偏移两种;PopupWindow是不阻塞的对话框,AlertDialog是阻塞对话框。按照参照类型不同又可以分为两种:相对某个控件(Anchor锚)的位置和父容器内部的相对位置。具体如下:

 

函数简介 

showAsDropDown(View anchor)

相对某个控件的位置(正左下方),无偏移

showAsDropDown(View anchor, int xoff, int yoff)

相对某个控件的位置,有偏移(正数表示下方右边,负数表示(上方左边))

showAtLocation(View parent, int gravity, int x, int y)

父容器容器相对位置,例如正中央Gravity.CENTER,下方Gravity.BOTTOM

 

 

注:PopupWindow弹出时,Activity不会调用onPause(),即它不会阻塞调用它的Activity

 

主程序:

package com.example.painttest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

public class PopupDemo extends Activity {

	private Button buttonDefault;
	private Button buttonThree;
	private Button buttonLocation;
	private Button close;
	private PopupWindow pop;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//获得控件的引用
		buttonDefault = (Button)findViewById(R.id.buttonDefault);
		buttonThree = (Button)findViewById(R.id.buttonThree);
		buttonLocation = (Button)findViewById(R.id.buttonLocation);
		//在onCreate中队PopupWindow进行初始化
		initPopupWindow();
		//给按键设置监听器
		buttonDefault.setOnClickListener(new ButtonListener());
		buttonThree.setOnClickListener(new ButtonListener());
		buttonLocation.setOnClickListener(new ButtonListener());
	}
	//按键监听器类
	class ButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.buttonDefault:			//使用带一个参数的showAsDropDown()方法,把PopupWindow放在触发它的窗体右下角
				if (pop.isShowing()) {
					pop.dismiss();
				}else {
					pop.showAsDropDown(v);
				}
				break;
			case R.id.buttonThree:			//使用带三个参数的showAsDropDown()方法,把PopupWindow放置在触发它的窗体的右下角相对移动X,Y的位置处
				if (pop.isShowing()) {
					pop.dismiss();
				}else {
					pop.showAsDropDown(v, 0, -200);
				}
				break;
			case R.id.close:			//PopupWindow上的按键对应的事件处理。
				pop.dismiss();
				break;
			default:
				if (pop.isShowing()) {
					pop.dismiss();
				} else {
					pop.showAtLocation(v, Gravity.CENTER_VERTICAL, 100, 100);
				}
				break;
			}
		}
		
	}
	
	public void initPopupWindow() {
		View view = this.getLayoutInflater().inflate(R.layout.popupwindow, null);		//通过Infalter使用布局文件得到PopupWindow视图
		pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);//设置PopupWindow的布局
											
		pop.setOutsideTouchable(true);				//设置PopupWindow外是否可以触摸
		
		view.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
			}
		});
		try {
			close = (Button)view.findViewById(R.id.close);
			close.setOnClickListener(new ButtonListener());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}

	
}

主界面布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/textHint"
        android:textSize="20sp" />

    <Button
        android:id="@+id/buttonDefault"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView"
        android:layout_marginTop="24dp"
        android:text="@string/buttonDefault" />

    <Button
        android:id="@+id/buttonThree"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/buttonDefault"
        android:layout_marginTop="24dp"
        android:text="@string/buttonThree" />

    <Button
        android:id="@+id/buttonLocation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="@string/buttonLoaction" />

</RelativeLayout>

PopupWindow布局窗口:

<?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="fill_parent"
    android:background="#d0d0d0"
    android:orientation="vertical" >




    <Button
        android:id="@+id/close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/colse" />

</LinearLayout>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤实现: 1. 创建一个PopupWindow对象,并设置其宽度和高度。 ``` PopupWindow popupWindow = new PopupWindow(context); popupWindow.setWidth(editText.getWidth()); popupWindow.setHeight(height); ``` 2. 创建一个RecyclerView对象,并设置其布局管理器和适配器。 ``` RecyclerView recyclerView = new RecyclerView(context); recyclerView.setLayoutManager(new LinearLayoutManager(context)); recyclerView.setAdapter(adapter); ``` 3. 创建一个Adapter对象,用于显示最近五条输入记录。在Adapter中,可以从SharedPreferences中获取保存的输入记录,并在列表中显示。 ``` public class RecordAdapter extends RecyclerView.Adapter<RecordAdapter.RecordViewHolder> { private List<String> recordList; public RecordAdapter(List<String> recordList) { this.recordList = recordList; } @NonNull @Override public RecordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_record, parent, false); return new RecordViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecordViewHolder holder, int position) { String record = recordList.get(position); holder.recordText.setText(record); } @Override public int getItemCount() { return recordList.size(); } static class RecordViewHolder extends RecyclerView.ViewHolder { TextView recordText; public RecordViewHolder(View itemView) { super(itemView); recordText = itemView.findViewById(R.id.record_text); } } } ``` 4. 在EditText的点击事件中,显示PopupWindow,并将RecyclerView添加到PopupWindow中。 ``` editText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View contentView = LayoutInflater.from(context).inflate(R.layout.popup_window, null); RecyclerView recyclerView = contentView.findViewById(R.id.record_list); RecordAdapter adapter = new RecordAdapter(recordList); recyclerView.setAdapter(adapter); PopupWindow popupWindow = new PopupWindow(contentView, editText.getWidth(), height, true); popupWindow.showAsDropDown(editText); } }); ``` 5. 在Activity的onPause()方法中,保存最近五条输入记录到SharedPreferences中。 ``` @Override protected void onPause() { super.onPause(); SharedPreferences.Editor editor = getSharedPreferences("record", MODE_PRIVATE).edit(); if (recordList.size() > 5) { recordList = recordList.subList(0, 5); } Set<String> recordSet = new HashSet<>(recordList); editor.putStringSet("recordList", recordSet); editor.apply(); } ``` 完整代码如下: ``` public class MainActivity extends AppCompatActivity { private EditText editText; private List<String> recordList = new ArrayList<>(); private int height; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.edit_text); // 获取屏幕高度 DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); height = (int) (displayMetrics.heightPixels * 0.3); // 从SharedPreferences中获取最近五条输入记录 SharedPreferences sharedPreferences = getSharedPreferences("record", MODE_PRIVATE); Set<String> recordSet = sharedPreferences.getStringSet("recordList", null); if (recordSet != null) { recordList.addAll(recordSet); } // 监听EditText的输入事件 editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { String input = s.toString().trim(); if (!TextUtils.isEmpty(input) && !recordList.contains(input)) { recordList.add(0, input); } } }); // 点击EditText显示PopupWindow editText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_window, null); RecyclerView recyclerView = contentView.findViewById(R.id.record_list); RecordAdapter adapter = new RecordAdapter(recordList); recyclerView.setAdapter(adapter); PopupWindow popupWindow = new PopupWindow(contentView, editText.getWidth(), height, true); popupWindow.showAsDropDown(editText); } }); } @Override protected void onPause() { super.onPause(); SharedPreferences.Editor editor = getSharedPreferences("record", MODE_PRIVATE).edit(); if (recordList.size() > 5) { recordList = recordList.subList(0, 5); } Set<String> recordSet = new HashSet<>(recordList); editor.putStringSet("recordList", recordSet); editor.apply(); } public class RecordAdapter extends RecyclerView.Adapter<RecordAdapter.RecordViewHolder> { private List<String> recordList; public RecordAdapter(List<String> recordList) { this.recordList = recordList; } @NonNull @Override public RecordViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_record, parent, false); return new RecordViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecordViewHolder holder, int position) { String record = recordList.get(position); holder.recordText.setText(record); } @Override public int getItemCount() { return recordList.size(); } static class RecordViewHolder extends RecyclerView.ViewHolder { TextView recordText; public RecordViewHolder(View itemView) { super(itemView); recordText = itemView.findViewById(R.id.record_text); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值