1, 导入依赖 implementation ‘com.squareup:otto:1.3.8’
2, 定义一个类 AppBus, 继承Bus , ---- 单例模式 , 返回Bus 的子类对象
3, 注册到Bus 的主线程中 AppBus.getInstance().register(this);
4, 在onDestry() 方法中取消注册 @Override protected void onDestroy() { super.onDestroy(); AppBus.getInstance().unregister(this); }
5, 声明订阅者 @Subscribe public void receiveMessage(String result) { Toast.makeText(this, "result = " + result, Toast.LENGTH_SHORT).show(); }
6, 发起订阅 – 主线程中
AppBus.getInstance().post(“OTTO 返回的数据”);
自带ListView的Fragment 首先自定义继承ListFragment 然后重写onCreate方法 调用setListAdapter(),为ListView控件赋值 重写onListItemClick()实现listview的点击事件
代码如下:
public class ListFragment_1 extends ListFragment { ArrayList<Goods> objects = new ArrayList<>(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); objects.clear(); objects.add(new Goods(R.mipmap.shouji1,"iQOO 8GB+128GB 电光蓝","3298")); objects.add(new Goods(R.mipmap.shouji2,"X27 8GB+256GB 雀羽蓝","3598")); objects.add( new Goods(R.mipmap.shouji3,"NEX旗舰版8GB+256GB 星钻黑","4998")); objects.add(new Goods(R.mipmap.shouji4,"S1 6GB+128GB 冰湖蓝","3298")); objects.add( new Goods(R.mipmap.shouji5,"Z3x 4GB+64GB 极光色","1198")); setListAdapter(new MyAdapter(objects,getContext())); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { Goods goods = objects.get(position); Toast.makeText(getContext(), goods.title+"已添加到购物车", Toast.LENGTH_SHORT).show(); Gongyong.goods.add(goods); } }自定义继承DialogFragment,找到布局即可; 调用方法与其他Fragment不同
public class Dia extends DialogFragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.item,container,false); } }调用方法如下:
Dia dia = new Dia(); dia.show(supportFragmentManager,"ssss");布局文件:
<android.support.v4.view.ViewPager android:id="@+id/page" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.PagerTitleStrip android:layout_width="match_parent" android:layout_height="50dp"> </android.support.v4.view.PagerTitleStrip> </android.support.v4.view.ViewPager>具体实现:
ArrayList<ImageView> objects = new ArrayList<>(); ImageView imageView = new ImageView(this); imageView.setImageResource(R.mipmap.yindaoye); ImageView imageView2 = new ImageView(this); imageView2.setImageResource(R.mipmap.yindaoye); ImageView imageView3 = new ImageView(this); imageView3.setImageResource(R.mipmap.yindaoye); objects.add(imageView); objects.add(imageView2); objects.add(imageView3); ArrayList<String> objects1 = new ArrayList<>(); objects1.add("哈哈哈"); objects1.add("吼吼吼"); objects1.add("呵呵呵"); MyPagerAdapter myPagerAdapter = new MyPagerAdapter(objects,objects1); viewPager.setAdapter(myPagerAdapter);