學習EventBus的記錄
來自: http://blog.csdn.net//chenguang79/article/details/50516752
EventBus現在的應用比較廣泛。要是你還沒有聽說過,或是沒有用到,就有點out了。https://github.com/greenrobot/EventBus這是地址。
這里推薦一個blog大家可以去看一下,相當的不錯
http://blog.csdn.net/lmj623565791/article/details/40920453與http://blog.csdn.net/lmj623565791/article/details/40794879,作者做了簡單的例子,而且對源碼進行了分析了。這里我把自己做的例子,放在此處,做一個記錄。
例子,比較簡單,一共兩個功能,一個是從訪問網上數據,通過 webserves來讀取相關的數據,顯示在頁面當中,另一個就是我們現在常用的DrawerLayout來切換菜單。
一,訪問網絡下載加載到listview中
直接上代碼:
activity_loading_data.xml主布局
<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"
tools:context="com.example.cg.eventbuslearn.LoadingDataActivity"
android:orientation="vertical">
<include
layout="@layout/toolbar" />
<ListView
android:id="@+id/lv_loadingdata"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout> activity_loadingdata_item.xml Item布局
<?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="match_parent">
<TextView
android:id="@+id/txt_loadingdata_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"/>
</LinearLayout> LoadingData_Adatper.java 加載數據的Adapter
package com.example.cg.eventbuslearn.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.cg.eventbuslearn.R;
import java.util.List;
/**
* 加載遠程數據Adapter
* Created by cg on 2016/1/13.
*/
public class LoadingData_Adatper extends BaseAdapter {
List<String> list_data;
LayoutInflater inflater;
public LoadingData_Adatper(Context context,List<String> list_data) {
this.inflater = LayoutInflater.from(context);
this.list_data = list_data;
}
@Override
public int getCount() {
return list_data.size();
}
@Override
public Object getItem(int position) {
return list_data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
loadingDataItem ldt;
if(convertView==null)
{
ldt = new loadingDataItem();
convertView = inflater.inflate(R.layout.activity_loadingdata_item,null);
ldt.name = (TextView)convertView.findViewById(R.id.txt_loadingdata_name);
convertView.setTag(ldt);
}else
{
ldt = (loadingDataItem)convertView.getTag();
}
ldt.name.setText(list_data.get(position));
return convertView;
}
class loadingDataItem
{
TextView name;
}
} LoadingDataActivity.java 主程序
package com.example.cg.eventbuslearn;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ListView;
import com.example.cg.eventbuslearn.Adapter.LoadingData_Adatper;
import com.example.cg.eventbuslearn.untils.webservicesUntils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
public class LoadingDataActivity extends AppCompatActivity {
private Toolbar toolbar; //定義toolbar
private ListView lv_loadingdata;
private LoadingData_Adatper lAdatper;
private List<String> list_data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading_data);
toolbar = (Toolbar) this.findViewById(R.id.toolbar);
toolbar.setTitle("EventBus加載遠程數據");
setSupportActionBar(toolbar);
//訂閱事件
EventBus.getDefault().register(this);
initControls();
initData();
}
/**
* 初始化數據
*/
private void initData() {
list_data = new ArrayList<>();
lAdatper = new LoadingData_Adatper(this,list_data);
lv_loadingdata.setAdapter(lAdatper);
new Thread(new Runnable() {
@Override
public void run() {
try {
String soapObject = webservicesUntils.getIndexItemList("", "", 1, 10);
//Log.e("soapObject",soapObject);
if (soapObject != "0") {
try {
JSONArray jsonArray = new JSONArray(soapObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
list_data.add(jsonObject2.getString("questionTitle"));
}
EventBus.getDefault().post(list_data);
} catch (JSONException e) {
// TODO Auto-generated catch block
//Log.e("error",e.getMessage().toString());
e.printStackTrace();
}
}
} catch (Exception ex) {
}
}
}).start();
}
/**
* 加載數據
* @param event
*/
public void onEventMainThread(List<String> event)
{
lAdatper.notifyDataSetChanged();
}
/**
* 初始化控件
*/
private void initControls() {
lv_loadingdata = (ListView)findViewById(R.id.lv_loadingdata);
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消注冊
EventBus.getDefault().unregister(this);
}
} 二,通過DrawerLayout切換菜單
activity_fragment_to_fragment.xml主布局
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="@layout/toolbar" />
<!-- 內容界面 -->
<FrameLayout
android:id="@+id/frame_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- 側滑菜單內容 -->
<fragment
android:id="@+id/navigation_drawer"
android:name="com.example.cg.eventbuslearn.untils.tool_NavigationDrawerFragment"
android:layout_width="@dimen/navigationWidth"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout> toolbar.xml toolbar布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar">
</android.support.v7.widget.Toolbar> fragment_main_drawer.xml DrawerLayout布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<LinearLayout
android:id="@+id/linear_drawer_login"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:orientation="vertical"
android:background="#3A5FCD">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical">
<com.example.cg.eventbuslearn.untils.CircleImageView
android:id="@+id/img_userPic"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:src="@drawable/img_empty_followers"
app:border_width="1dp"
app:border_color="@color/white"
/>
</LinearLayout>
<TextView
android:id="@+id/txt_main_drawer_UserNick"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="我本無名"
android:textColor="@color/white"
android:layout_marginLeft="10dp"/>
<TextView
android:id="@+id/txt_main_drawer_UserProfile"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="碼農"
android:textSize="@dimen/main_drawer_small"
android:textColor="@color/white"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<ListView
android:id="@+id/lv_main_drawer_leftmenu"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="6"
android:background="@color/white"
android:choiceMode="singleChoice"
android:layout_marginTop="5dp"
android:divider="@null"
android:scrollbars="none"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="@color/white"
android:layout_marginTop="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ImageView
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="@color/grey"
android:contentDescription="@string/Guide_fragment_img_Description"/>
</LinearLayout>
<LinearLayout
android:id="@+id/linear_drawer_chanageStyle"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:background="@drawable/main_drawer_background"
android:clickable="true"
android:gravity="center_vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="@string/navigation_Menu_changeStyle"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@drawable/main_drawer_text_color"
/>
</LinearLayout>
<LinearLayout
android:id="@+id/linear_drawer_setting"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:background="@drawable/main_drawer_background"
android:clickable="true"
android:gravity="center_vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:text="@string/navigation_Menu_setting"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@drawable/main_drawer_text_color"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</FrameLayout> fragment_main_drawer_item.xml DrawerLayout中可點擊菜單布局
<?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="match_parent"
android:padding="16dp"
android:gravity="center_vertical"
android:background="@drawable/main_drawer_background"
android:orientation="horizontal">
<ImageView
android:id="@+id/item_icon"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="@drawable/main_drawer_text_color"
android:gravity="center_vertical"
/>
</LinearLayout> tool_NavigationDrawerFragment.java
package com.example.cg.eventbuslearn.untils;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.example.cg.eventbuslearn.Adapter.Main_Drawer_lv_Adapter;
import com.example.cg.eventbuslearn.R;
import com.example.cg.eventbuslearn.bean.MainDrawerMenu;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
/**
* 左側側滑菜單的fragment
* Created by cg on 2015/8/26.
*/
public class tool_NavigationDrawerFragment extends Fragment implements View.OnClickListener {
private ListView lv_main_drawer_leftmenu; //定義菜單的listView
private List<MainDrawerMenu> list_menu;
private LinearLayout linear_drawer_login; //定義用戶登錄之后的頁面布局
private LinearLayout linear_drawer_noLogin; //定義用戶未登錄之后的頁面布局
private TextView txt_drawer_nologin_login; //定義登錄注冊按鈕
private CircleImageView img_userPic; //用戶圖片
private TextView txt_main_drawer_UserNick; //用戶姓名
private TextView txt_main_drawer_UserProfile; //用戶簡介
private LinearLayout linear_drawer_chanageStyle; //切換主題
private LinearLayout linear_drawer_setting; //設置
private LinearLayout linear_drawer_nostyle;
private LinearLayout linear_drawer_nosetting;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main_drawer,container,false);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
super.onDestroy();
//EventBus.getDefault().unregister(this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lv_main_drawer_leftmenu = (ListView)view.findViewById(R.id.lv_main_drawer_leftmenu);
list_menu = getMenuItem();
lv_main_drawer_leftmenu.setAdapter(new Main_Drawer_lv_Adapter(getActivity(), list_menu));
lv_main_drawer_leftmenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EventBus.getDefault().post(list_menu.get(position).getMainDrawer_menuName());
}
});
linear_drawer_login = (LinearLayout)view.findViewById(R.id.linear_drawer_login);
img_userPic = (CircleImageView)view.findViewById(R.id.img_userPic);
txt_main_drawer_UserNick = (TextView)view.findViewById(R.id.txt_main_drawer_UserNick);
txt_main_drawer_UserProfile = (TextView)view.findViewById(R.id.txt_main_drawer_UserProfile);
linear_drawer_chanageStyle = (LinearLayout)view.findViewById(R.id.linear_drawer_chanageStyle);
linear_drawer_chanageStyle.setOnClickListener(this);
linear_drawer_setting = (LinearLayout)view.findViewById(R.id.linear_drawer_setting);
linear_drawer_setting.setOnClickListener(this);
}
/**
* 從arrays.xml中取出數據,裝入list<T>中
* @return 返回菜單名稱列表
*/
private List<MainDrawerMenu> getMenuItem()
{
List<MainDrawerMenu> list_menu = new ArrayList<MainDrawerMenu>();
String[] itemTitle = getResources().getStringArray(R.array.item_title);
TypedArray itemIconRes = getResources().obtainTypedArray(R.array.item_icon_res);
for(int i=0;i<itemTitle.length;i++)
{
MainDrawerMenu lmi = new MainDrawerMenu();
lmi.setMainDrawer_icon(itemIconRes.getResourceId(i,0));
lmi.setMainDrawer_menuName(itemTitle[i]);
list_menu.add(lmi);
}
return list_menu;
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.linear_drawer_chanageStyle:
break;
case R.id.linear_drawer_setting:
break;
}
}
} 主程序 FragmentToFragmentActivity.java
package com.example.cg.eventbuslearn;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import de.greenrobot.event.EventBus;
/**
* 實現的是左側Fragment點擊事件,主頁面得到
* 這里注意一點的是,因為我們的布局,左側側滑布局也是在主頁面當中的,所以在tool_NavigationDrawerFragment.java不要進行注冊。直接在此頁注冊就OK了
*/
public class FragmentToFragmentActivity extends AppCompatActivity {
private Toolbar toolbar; //定義toolbar
private DrawerLayout drawer_main; //定義左側滑動布局,其實就是主布局
private ftf_IndexFragment iFragment;
private ftf_FindFragment fFragment;
private ftf_AttentionFragment aFragment;
private ftf_CollectionFragment cFragment;
private ftf_DraftFragment dFragment;
private Fragment isFragment; //記錄當前正在使用的fragment
/**
* 供其它頁面調用
* @param context 上下文
*/
public static void FragmentToFragmentStart(Context context)
{
Intent intent = new Intent(context,FragmentToFragmentActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_to_fragment);
EventBus.getDefault().register(this);
toolbar = (Toolbar) this.findViewById(R.id.toolbar);
toolbar.setTitle("Fragment之間的傳值");
setSupportActionBar(toolbar);
//為了生成,工具欄左上角的動態圖標,要使用下面的方法
drawer_main = (DrawerLayout) findViewById(R.id.drawer_main);
initFragment(savedInstanceState);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
/**
* 當fragment進行切換時,采用隱藏與顯示的方法加載fragment以防止數據的重復加載
* @param from
* @param to
*/
public void switchContent(Fragment from, Fragment to) {
if (isFragment != to) {
isFragment = to;
FragmentManager fm = getSupportFragmentManager();
//添加漸隱漸現的動畫
FragmentTransaction ft = fm.beginTransaction();//.setCustomAnimations(
// android.R.animator.fade_in, android.R.animator.fade_out);
//FragmentTransaction ft = fm.beginTransaction().setCustomAnimations(R.anim.in_from_right_fragment,R.anim.out_to_left_fragment);
if (!to.isAdded()) { // 先判斷是否被add過
ft.hide(from).add(R.id.frame_main, to).commit(); // 隱藏當前的fragment,add下一個到Activity中
} else {
ft.hide(from).show(to).commit(); // 隱藏當前的fragment,顯示下一個
}
}
}
/**
* 為頁面加載初始狀態的fragment
*/
public void initFragment(Bundle savedInstanceState)
{
//判斷activity是否重建,如果不是,則不需要重新建立fragment.
if(savedInstanceState==null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (iFragment == null) {
iFragment = new ftf_IndexFragment();
}
isFragment = iFragment;
ft.replace(R.id.frame_main, iFragment).commit();
}
}
public void onEventMainThread(String menuName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
switch (menuName)
{
case "首頁" :
if(iFragment!=null) {
iFragment = new ftf_IndexFragment();
}
switchContent(isFragment,iFragment);
break;
case "發現" :
if(fFragment==null)
{
fFragment = new ftf_FindFragment();
}
switchContent(isFragment,fFragment);
break;
case "關注" :
if(aFragment==null)
{
aFragment = new ftf_AttentionFragment();
}
switchContent(isFragment,aFragment);
break;
case "收藏" :
if(cFragment==null)
{
cFragment = new ftf_CollectionFragment();
}
switchContent(isFragment,cFragment);
break;
case "草稿" :
if(dFragment==null)
{
dFragment = new ftf_DraftFragment();
}
switchContent(isFragment,dFragment);
break;
case "提問" :
break;
case "切換主題":
Toast.makeText(this, "對不起,無樣式可以切換", Toast.LENGTH_SHORT).show();
break;
case "設置":
break;
}
invalidateOptionsMenu();
/**
* 關閉左側滑出菜單
*/
drawer_main.closeDrawers();
}
} 本文由用戶 Daniel131 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!