1. 程式人生 > >Android popwindow和fragment結合 左側彈出下拉選單 切換介面

Android popwindow和fragment結合 左側彈出下拉選單 切換介面

      延續上一篇文章Android 實現對話方塊圓角功能 ,在專案推進的過程當中,之前是已經用popwindow實現了點選按鈕,在按鈕下方彈出下拉選單,實現了類似微信右上角加好友的功能,有興趣的朋友,可以下載這個資源。迴歸主題,之前popwindow的使用,是固定在了登陸剛進去的介面,假設現在點選了左側選單的其他按鈕,這就要求標題下方的內容必須更新所要顯示的內容,一開始想都沒想,就用瞭如下程式碼進行跳轉:

Intent intent = new Intent(Intent.ACTION_EDIT, null);
startActivity(intent);
       這樣做的確是能跳轉到另一個顯示介面,但所有的xml檔案、下拉popwindow選單,都得重新在activity重複使用,關鍵是跳轉到這個介面,如果點選下拉選單的其他按鈕,這個時候又得重新寫
Intent intent = new Intent(Intent.ACTION_EDIT, null);
 startActivity(intent);
    陷入了一個死迴圈,假設有10個選單項,我就得寫相同的程式碼10次,而且intent跳來跳去的,程式碼太亂,無法進行管理,非常難以忍受。所以就想著android應該有提供這樣的類可以保持左側不變,或者其他部分可以動態更新,很高興找到了actvitygroup這個類,下載的demo執行之後,的確是能解決,但已經不推薦使用這個類,所以就決定使用fragment來進行介面的動態切換。下面是工程程式碼:

     1.主介面檔案,裡面存放著一個FrameLayout,可以用你想呈現的介面進行更換,也就是fragment,類似於單獨的activity。

<LinearLayout 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"
   android:orientation="vertical"
    tools:context=".MainActivity" >
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="@color/menu_background"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/popBtn"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginTop="8dp"
            android:background="@drawable/image2"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="測試"
            android:textColor="@color/white"
            android:textSize="30dp" />

        <Button
            android:id="@+id/menu_person"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_marginTop="8dp"
            android:background="@drawable/image1" />
    </RelativeLayout>

    <span style="font-size:18px;color:#ff0000;background-color: rgb(255, 255, 102);"><strong>//這是關鍵點,用來動態替換frament,更換介面</strong></span>
    <FrameLayout 
        android:id="@+id/fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:background="@color/background"
        />
</LinearLayout>

           2.定義好了主介面,就得編寫你要替換的介面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="@color/background"
    android:orientation="vertical" >
    <!-- 使用者狀態列 -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="25dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="測試"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:id="@+id/price_trademargin"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="測試"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:id="@+id/price_floatpl"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="12dp" />
    </LinearLayout>

</LinearLayout>
       第二個fragment2的佈局檔案:
<?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="@color/background"
    android:orientation="vertical">

    <!-- 使用者狀態列 -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="25dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/trademargin"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:id="@+id/price_trademargin"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="@string/floatpl"
            android:textColor="@color/white"
            android:textSize="12dp" />

        <TextView
            android:id="@+id/price_floatpl"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="12dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="@dimen/activity_price_inst_width"
            android:layout_height="@dimen/price_table_comm_height"
            android:background="@drawable/tableheader"
            android:gravity="center"
            android:text="@string/price_table_ccy"
            android:textColor="@color/price_tableheader_forcolor"
            android:textSize="@dimen/price_table_header_font_size" />

        <TextView
            android:layout_width="@dimen/activity_price_chart_width"
            android:layout_height="@dimen/price_table_comm_height"
            android:background="@drawable/tableheader"
            android:gravity="center"
            android:text=""
            android:textColor="@color/white" />

        <com.android.fragmentnormal.AlloneHorizontalScrollView
            android:id="@+id/HorizontalScrollView_1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none" >
        </com.android.fragmentnormal.AlloneHorizontalScrollView>
    </LinearLayout>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/background" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:background="@color/background" >

            <TableLayout
                android:id="@+id/left_table"
                android:layout_width="@dimen/price_left_table_width"
                android:layout_height="fill_parent"
                android:background="@color/background"
                android:orientation="vertical" >
            </TableLayout>

            <com.android.fragmentnormal.AlloneHorizontalScrollView
                android:id="@+id/HorizontalScrollView_2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/left_table"
                android:background="@color/background" >

                <TableLayout
                    android:id="@+id/data_table"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:background="@color/background"
                    android:orientation="vertical" >
                </TableLayout>
            </com.android.fragmentnormal.AlloneHorizontalScrollView>
        </RelativeLayout>
    </ScrollView>

</LinearLayout>

      3.編寫主類,對你的兩個fragment進行管理,決定一開始顯示哪個,點選按鈕之後切換顯示哪個fragment。
package com.android.fragmentnormal;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

public class MainActivity extends FragmentActivity  {
	FragmentManager manager ;
	Fragment f1,f2,f3 ;
	Button pop;
	private PopupWindow popupWindow;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		manager= getSupportFragmentManager() ;
		FragmentTransaction transaction = manager.beginTransaction() ;
		f1 = new Fragment1();
		f2 = new Fragment2();
		f3 = new Fragment3();

		pop = (Button) findViewById(R.id.popBtn);
		pop.setOnClickListener(popClick);

		transaction.add(R.id.fragment_container, f2);
		transaction.commit();
	}

	// 點選彈出左側選單的顯示方式
	OnClickListener popClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			/*Toast toast = Toast.makeText(MainActivity.this, "這是一個代圖片的Toast!", Toast.LENGTH_LONG);
			toast.show();*/

			getPopupWindow();

			// 這裡是位置顯示方式,在按鈕的左下角
			popupWindow.showAsDropDown(v);
		}
	};


	/**
	 * 建立PopupWindow
	 */
	protected void initPopuptWindow() {
		// 獲取自定義佈局檔案pop.xml的檢視
		View popupWindow_view = getLayoutInflater().inflate(R.layout.pop, null,
				false);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		// 建立PopupWindow例項,200,150分別是寬度和高度
		popupWindow = new PopupWindow(popupWindow_view, 350,
				ViewGroup.LayoutParams.MATCH_PARENT, true);
		// popupWindow.setWidth(350);
		// popupWindow.setHeight(dm.heightPixels * 20 / 2);
		// 設定動畫效果
		popupWindow.setAnimationStyle(R.style.AnimationFade);
		// 點選其他地方消失
		popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});
		// pop.xml視圖裡面的控制元件
		initOpenMenuItem(popupWindow_view);
		initOpenMenuOther(popupWindow_view);
		initOpenPosition(popupWindow_view);

	}
	/*
     *  2015年7月13日17:35:24,
     *  author:qiulinhe
     *  新增對於開倉單的監聽和介面增加
     */
	private void initOpenPosition(View popupWindow_view) {
		DrawableCenterTextView menu_open = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_open);
		// pop.xml視圖裡面的控制元件觸發的事件

		menu_open.setOnClickListener(new OnClickListener() {
			<span style="font-size:18px;color:#ff0000;"><strong>FragmentTransaction transaction ;//對fragment進行跳轉控制。</strong></span>
			@Override
			public void onClick(View v) {
				<strong><span style="font-size:18px;color:#ff0000;">transaction = manager.beginTransaction();
				transaction.replace(R.id.fragment_container, f1);//把f1的介面替換container
				transaction.commit();
				popupWindow.dismiss();</span></strong>
			}
		});

	}

        <strong><span style="font-size:18px;color:#33cc00;">//初始化左側下拉選單的按鈕</span></strong>
	private void initOpenMenuOther(View popupWindow_view) {
		DrawableCenterTextView menu_open = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_open);
		DrawableCenterTextView menu_order = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_order);
		DrawableCenterTextView menu_orderhis = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_orderhis);
		DrawableCenterTextView menu_closehis = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_closehis);
		DrawableCenterTextView menu_summary = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_summary);
		DrawableCenterTextView menu_pricewarning = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_pricewarning);
		DrawableCenterTextView menu_news = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_news);
		DrawableCenterTextView menu_margin = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_margin);
		DrawableCenterTextView menu_message = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_message);
		DrawableCenterTextView menu_syssett = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_syssett);
		DrawableCenterTextView menu_about = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_about);
	}

	private void initOpenMenuItem(View popupWindow_view) {
		DrawableCenterTextView menu_price = (DrawableCenterTextView) popupWindow_view
				.findViewById(R.id.menu_price);
		// 開啟
		menu_price.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});
	}

	/***
	 * 獲取PopupWindow例項
	 */
	private void getPopupWindow() {

		if (null != popupWindow) {
			popupWindow.dismiss();
			return;
		} else {
			initPopuptWindow();
		}
	}

}
        4.frament1的程式碼如下:
package com.android.fragmentnormal;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.Toast;

public class Fragment1 extends Fragment{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		<span style="color:#ff0000;"><strong>View vi = inflater.inflate(R.layout.activity_openposition, container,false);</strong></span>



		//實現下方長按彈出listview,2015年7月14日10:01:19
		ActionSlideExpandableListView list = (ActionSlideExpandableListView)vi.findViewById(R.id.list);


		list.setAdapter(buildDummyData());

		list.setItemActionListener(
				new ActionSlideExpandableListView.OnActionClickListener() {

					@Override
					public void onClick(View listView, View buttonview,
										int position) {
						String actionName = "";
						if (buttonview.getId() == R.id.duichong) {
							actionName = "duichong";
						}
						Toast.makeText(
								getActivity(),
								"你點選了對衝按鈕",
								Toast.LENGTH_SHORT).show();
					}

				}, R.id.duichong);
		return vi;
	}


	/**
	 * qiulinhe
	 * 2015年7月14日10:02:03
	 * 實現開倉單下方長按,彈出兩個按鈕功能
	 */
	public ListAdapter buildDummyData() {
		final int SIZE = 20;
		String[] values = new String[SIZE];
		for (int i = 0; i < SIZE; i++) {
			values[i] = "單號";
		}
		return new ArrayAdapter<String>(getActivity(), R.layout.expandable_list_item,
				R.id.text, values);
	}
}

   5.fragment2的程式碼如下:
package com.android.fragmentnormal;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.frament2, container,false);
	}
}

     程式碼基本完畢,如果想要demo可以到這個連結:csdn資源可以下載點選開啟連結,其實原理很簡單,就是通過fragment來管理切換介面。

執行介面如下:



     新增另外一個問題:這個彈出popwindow,點選任何地方都會讓彈窗消失,如何使其重新點選選單,才能消失呢,實現方法如下:

   1.首先設定整個螢幕的背景。

   2.捕獲點選事件

  程式碼如下:

popupWindow.setOnDismissListener(new OnDismissListener() {
<span style="white-space:pre">		</span>@Override
<span style="white-space:pre">		</span>public void onDismiss() {
<span style="white-space:pre">			</span>backgroundAlpha(1f);
<span style="white-space:pre">		</span>  }
<span style="white-space:pre">		</span>});
// 設定螢幕背景
	private void backgroundAlpha(float alpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = alpha; // 0.0-1.0
		getWindow().setAttributes(lp);
	}

// 點選其他地方消失
		popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupWindow != null && popupWindow.isShowing()
						&& <span style="font-size:24px;color:#ff0000;">event.getAction() == MotionEvent.ACTION_OUTSIDE</span>) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});