学习EventBus的记录

Daniel131 8年前

来自: 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();      }  }