Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android利用廣播實現ViewPager中item之間的數據通信

Android利用廣播實現ViewPager中item之間的數據通信

編輯:關於Android編程

當你在實現Fragment之間的通信時(例如Fragment_A和Fragment_B),可能會想到的方法是在Fragment_B中對外提供一個接口,然後在Fragment_A中去調用這個接口,並把這需要的參數傳遞過去。

下面我將對利用廣播來實現從Fragment_A向Fragment_B傳遞數據。

主界面:

 

public class MainActivity extends FragmentActivity {

    private int getLayoutResID() {
        return R.layout.activity_main;
    }
    
    private MyViewPagerAdapter mAdapter = null;
    private final int START_ITEM = 0;
    private ViewPager mDataViewPager = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(getLayoutResID());
        
        initEvent();
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        initView();
    }
    
    /**
     * 初始化界面
     */
    private void initView() {
        initWidgets();
    }
    
    /**
     * 初始化控件
     */
    private void initWidgets() {
        mDataViewPager = (ViewPager) findViewById(R.id.activity_main_show_viewpager);
        
        mAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        mAdapter.setContext(MainActivity.this);
        mDataViewPager.setAdapter(mAdapter);
        mDataViewPager.setCurrentItem(START_ITEM);
    }
}

 

適配器:

 

public class MyViewPagerAdapter extends FragmentStatePagerAdapter {

	public static final int FRAGMENT_VIEWPAGER_PAGE_COUNT = 2;
	private Context mContext;
	
	public MyViewPagerAdapter(FragmentManager fm) {
		super(fm);
	}
	
	public void setContext(Context context) {
        mContext = context;
    }

	@Override
	public Fragment getItem(int which) {
		try {
			switch (which) {
			case 0:
				return PageOneFragment.newInstance();
			case 1:
				return PageTwoFragment.newInstance();

			default:
				break;
			}
		} catch(Exception e) {
		    e.printStackTrace();
		}
		return PageOneFragment.newInstance();
	}
	
	@Override
	public int getCount() {
		return FRAGMENT_VIEWPAGER_PAGE_COUNT;
	}
}

 

第一個Fragment:

 

 

public class PageOneFragment extends Fragment {

	public static PageOneFragment newInstance() {
		PageOneFragment fragment = new PageOneFragment();
		
		return fragment;
	}
	
	private int getLayoutResID() {
		return R.layout.fragment_page_0;
	}
	
	public static final String TAG = PageOneFragment.class.getName();
	private TextView mShowTextView = null;
	private Button mSendButton = null;
	
	private static final int MESSAGE_UPDATEVIEW = 0x123;
	
	private PageTwoDataChangedReceiver mReceiver = null;
	public static final String DATA_CHANGED = com.example.viewpager.communication.fragment.PAGE_ONE_DATA_CHANGED;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
	    
		View view = inflater.inflate(getLayoutResID(), container, false);
		
		initEvent(view);
		
		return view;
	}
	
	private void initEvent(View v) {
		initView(v);
		
		registerPageTwoDataChangedReceiver();
	}
	
	private void initView(View v) {
		initWidgets(v);
		
		setViewOnclickEvent();
	}
	
	private void initWidgets(View v) {
	    mShowTextView = (TextView) v.findViewById(R.id.page_0_show_textview);
	    mSendButton = (Button) v.findViewById(R.id.page_0_send_button);
	}
	
	/**
	 * 對所有的按鈕進行點擊事件監聽
	 */
	private void setViewOnclickEvent() {
	    mSendButton.setOnClickListener(viewOnClickListener);
	}
	
	private OnClickListener viewOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.page_0_send_button:
			    Intent intent = new Intent();
			    intent.setAction(PageTwoFragment.DATA_CHANGED);
			    getActivity().sendBroadcast(intent);
				break;

			default:
				break;
			}
		}
	};
	
	private void registerPageTwoDataChangedReceiver() {
	    IntentFilter filter = new IntentFilter();
	    try {
            if (mReceiver != null) {
                getActivity().unregisterReceiver(mReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	    
	    mReceiver = new PageTwoDataChangedReceiver();
	    filter.addAction(PageOneFragment.DATA_CHANGED);
	    getActivity().registerReceiver(mReceiver, filter);
	}
	
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_UPDATEVIEW:
				updateView((String)msg.obj);
				break;

			default:
				break;
			}
		};
	};
	
	private void updateView(String data) {
	    mShowTextView.setText(從第二頁發來的數據: + data +   + System.currentTimeMillis());
	}
	
	class PageTwoDataChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(PageOneFragment.DATA_CHANGED)) {
                String label = TWO Time: ;
                Message msg = new Message();
                msg.what = MESSAGE_UPDATEVIEW;
                msg.obj = label;
                handler.sendMessage(msg);
            }
        }
	}
	
	@Override
	public void onDestroy() {
	    if (mReceiver != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
	    
	    super.onDestroy();
	}
}

 

第二個Fragment:

 

 

public class PageTwoFragment extends Fragment {

	public static PageTwoFragment newInstance() {
		PageTwoFragment fragment = new PageTwoFragment();
		
		return fragment;
	}
	
	private int getLayoutResID() {
		return R.layout.fragment_page_1;
	}
	
	public static final String TAG = PageTwoFragment.class.getName();
	private static final int MESSAGE_UPDATEVIEW = 0x123;
	private TextView mShowTextView = null;
    private Button mSendButton = null;
	
	private PageOneDataChangedReceiver mReceiver = null;
	public static final String DATA_CHANGED = com.example.viewpager.communication.fragment.PAGE_TWO_DATA_CHANGED;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(getLayoutResID(), container, false);
		
		initEvent(view);
		
		return view;
	}
	
	private void initEvent(View v) {
		initView(v);
		
		registerPageOneDataChangedReceiver();
	}
	
	private void initView(View v) {
		initWidgets(v);
		
		setViewOnclickEvent();
	}
	
	private void initWidgets(View v) {
	    mShowTextView = (TextView) v.findViewById(R.id.page_1_show_textview);
        mSendButton = (Button) v.findViewById(R.id.page_1_send_button);
	}
	
	/**
	 * 對所有的按鈕進行點擊事件監聽
	 */
	private void setViewOnclickEvent() {
	    mSendButton.setOnClickListener(viewOnClickListener);
	}
	
	private OnClickListener viewOnClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.page_1_send_button:
			    Intent intent = new Intent();
                intent.setAction(PageOneFragment.DATA_CHANGED);
                getActivity().sendBroadcast(intent);
				break;

			default:
				break;
			}
		}
	};
	
    private void registerPageOneDataChangedReceiver() {
        IntentFilter filter = new IntentFilter();
        try {
            if (mReceiver != null) {
                getActivity().unregisterReceiver(mReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        mReceiver = new PageOneDataChangedReceiver();
        filter.addAction(PageTwoFragment.DATA_CHANGED);
        getActivity().registerReceiver(mReceiver, filter);
    }
    
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_UPDATEVIEW:
				updateView((String)msg.obj);
				break;

			default:
				break;
			}
		};
	};
	
	private void updateView(String data) {
        mShowTextView.setText(從第一頁發來的數據: + data +   + System.currentTimeMillis());
    }
	
    class PageOneDataChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(PageTwoFragment.DATA_CHANGED)) {
                String label = ONE Time: ;
                Message msg = new Message();
                msg.what = MESSAGE_UPDATEVIEW;
                msg.obj = label;
                handler.sendMessage(msg);
            }
        }
    }
	
    @Override
    public void onDestroy() {
        if (mReceiver != null) {
            getActivity().unregisterReceiver(mReceiver);
        }
        
        super.onDestroy();
    }
}

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved