PopupWindow自適應大小
阿新 • • 發佈:2019-01-10
private void showPopWindow(Context context, View parent) { // TODO Auto-generated method stub final PopupWindow pw; View myView; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); myView = inflater.inflate(R.layout.pop, null); Button pop_OK = (Button) myView.findViewById(R.id.button_ok); Button pop_Cancel = (Button) myView.findViewById(R.id.button_cancel); final EditText pop_User = (EditText) myView.findViewById(R.id.edittext); final EditText pop_Password = (EditText) myView.findViewById(R.id.password); pw = new PopupWindow(myView, 500, 200, true); pw.setWidth(LayoutParams.WRAP_CONTENT); pw.setHeight(LayoutParams.WRAP_CONTENT); pw.showAtLocation( myView, Gravity.TOP | Gravity.CENTER, 0, 0);
pop_OK.setOnClickListener(new OnClickListener() { public void onClick(View v) { //showPop_PopWindow(); // TODO Auto-generated method stub } }); pop_Cancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { pw.dismiss();// } }); pw.showAsDropDown(MyButton); }
只要程式碼中呼叫以上函式就可以了
XML檔案程式碼如下 pop.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffff00" android:orientation="vertical" > <TextView android:id="@+id/mytextview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" /> <TextView android:id="@+id/mytextview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="賬號" /> <EditText android:id="@+id/edittext" android:layout_width="180dip" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密碼" /> <EditText android:id="@+id/password" android:layout_width="180dip" android:layout_height="wrap_content" android:password="true" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffff00" android:orientation="horizontal" > <Button android:id="@+id/button_ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="確定" /> <Button android:id="@+id/button_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="取消" /> </LinearLayout> </LinearLayout>
以上紅色部分特別注意:
自適應螢幕
popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
view自適應
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout linearLayout = new LinearLayout(c);
linearLayout.setLayoutParams(params);
同樣的
pw.showAtLocation(view,Gravity.TOP | Gravity.LEFT, 252, 50);
以上面一句為例:第一個引數是指PopupWindow顯示在哪一個View之上.後面三個引數控制PopupWindow顯示的位置,此處表明PopupWindow顯示在距左上角x252個畫素,y50個畫素.
專案下載:http://download.csdn.net/detail/penglijiang/4419203