王学岗41jetpack的使用

新建项目注意勾选Androidx
在这里插入图片描述
一,监听生命周期

package com.example.lsn41_jetpack_20190920;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * 我们用这个观查者来盯好需要感知生命周期的对象
 */
public class MyLifeObserver implements LifecycleObserver {
    通过注解,只要Activity的onStart()方法跑起来,我们就会执行这个方法
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void onStartJett(LifecycleOwner activity){
               Log.i("zhang_xin","onCreate:"+activity.getClass().getName());
  }
}

这里最重要的就是这个注解,注解中除了Activity的常用的六个生命周期方法外,还有
Lifecycle.Event.ANY,表示在任何方法中调用
在onActivity中的onCreate()中或者在Fragment中调用

    //完成绑定,
        getLifecycle().addObserver(new MyLifeObserver());

看下运行效果
在这里插入图片描述
二:LiveDate和ViewModel
liveData可以用来保存数据,可以实时的通知UI更新
首先导入一个东西
implementation ‘androidx.lifecycle:lifecycle-extensions:2.0.0’
在这里插入图片描述
ViewModel的作用:将UI层数据和model层数据进行绑定

package com.example.lsn41_jetpack_20190920.viewmodel;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.lsn41_jetpack_20190920.R;
import com.example.lsn41_jetpack_20190920.bean.Girl;

import java.util.ArrayList;
import java.util.List;

public class MyGirl extends ViewModel {
    //定义一个对象,相当于一个用来存放数据的仓库。MutableLiveData继承自LiveData
    //注意这里必须是static,不然会报空指针异常,因为我们这里一个ViewModel对应多个Activity
    private static MutableLiveData<List<Girl>> liveData;
    //用于获取数据
    public LiveData<List<Girl>> getDataBean(){
        if(liveData==null){
            liveData=new MutableLiveData<>();
            loadData();
        }
        return liveData;
    }
    //数据可以从网络或者线程读取,我们这里先写死
    private void loadData() {
        List<Girl> data;
        data = new ArrayList<>();
        data.add(new Girl(R.drawable.f1, "一星", "****"));
        data.add(new Girl(R.drawable.f2, "一星", "****"));
        data.add(new Girl(R.drawable.f3, "一星", "****"));
        data.add(new Girl(R.drawable.f4, "一星", "****"));
        data.add(new Girl(R.drawable.f5, "一星", "****"));
        data.add(new Girl(R.drawable.f6, "一星", "****"));
        data.add(new Girl(R.drawable.f7, "一星", "****"));
        data.add(new Girl(R.drawable.f8, "一星", "****"));
        data.add(new Girl(R.drawable.f9, "一星", "****"));
        data.add(new Girl(R.drawable.f10, "一星", "****"));

        //把这些数据存放到仓库里面
        liveData.setValue(data);
    }

    //提供一个方法来改变数据,修改数据不需要使用EventBus,非常方便
    public void changeValue(int item,int i){
    //我把集合的内容改了,然后在放回去
        List<Girl> value = liveData.getValue();
        value.get(item).setLike(i+"");
        liveData.setValue(value);

    }
}

Girl是一个bean类,就不贴出来了,我们在MainActivity的onCreate()中调用

//调用系统API初始化这个对象,不需要使用new关键字。
        myGirl= ViewModelProviders.of(this).get(MyGirl.class);
        //myGirl.getDataBean()是得到这个仓库,设置一个人去监听这个仓库
        myGirl.getDataBean().observe(this, new Observer<List<Girl>>() {
            /**
             * 当我们的数据发生变化的时候,我们可以在这个onChanged中进行处理
             * @param girls
             */
            @Override
            public void onChanged(List<Girl> girls) {
                listView.setAdapter(new GirlAdapter(MainActivity.this,girls));
            }
        });

长按改变事件

  listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                myGirl.changeValue(position,1);
          return false;
            }
        });

在这里插入图片描述
大家可以发现这个更新是一个实时更新
即便是调到另一个Activity也一样可以更新数据

 listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                myGirl.changeValue(position,1);
                Intent intent=new Intent(MainActivity.this,SecActivity.class);
                MainActivity.this.startActivity(intent);
                return false;
            }
        });
package com.example.lsn41_jetpack_20190920;

import android.os.Bundle;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProviders;

import com.example.lsn41_jetpack_20190920.bean.Girl;
import com.example.lsn41_jetpack_20190920.viewmodel.MyGirl;

import java.util.List;

public class SecActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyGirl myGirl= ViewModelProviders.of(this).get(MyGirl.class);
        //一定要在主线程中调用,如果是在子线程,可以使用Handler把他发送到主线程
        //在这里修改数据,返回后发现数据已经改变,比eventbus好用,这句代码你可以写在任何地方
        myGirl.changeValue(0,666);
    }
}

当然以后我们会进一步完善,会把ViewModel和布局绑定
应用场景:股票实时变化
三,Activity与fragment之间的数据通信,我们以前多用EventBus,我们现在用livedata实现
我们去淘宝买华为手机,下订单后,华为手机发现后会给我们手机,在这里淘宝网就是总线。这是一个标准的观察者模式,华为手机会观察淘宝网。华为手机就是发布者,淘宝网是代理,我们普通用户是订阅者。
华为手机的实体类,


    package com.example.lsn41_jetpack_livedatabus_20190920;

public class Huawei {
    public String type;

    public Huawei(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


//这个类是我们的总线,就相当于我们买手机例子中的淘宝网
public class LiveDataBus {
    //用Map存放订阅者,用MutableLiveData存放数据
    private Map<String, MutableLiveData<Object>> bus;

    //单例
    private static LiveDataBus liveDataBus=new LiveDataBus();
    private LiveDataBus(){
        bus=new HashMap<>();
    }
    public static LiveDataBus getInstance(){
        return liveDataBus;
    }

    /**
     * 用来给用户进行订阅(存入map)
     * type给系统反射调用
     * 因为用的人多,考虑到多线程问题
     */
    public synchronized<T> MutableLiveData<T> with(String key,Class<T> type){
    //根据key值判断用户是否订阅过,如果已经订阅过直接去拿,没有就存到map里
        if(!bus.containsKey(key)){
            bus.put(key,new MutableLiveData<Object>());
        }
        return (MutableLiveData<T>) bus.get(key);
    }
   }
package com.example.lsn41_jetpack_livedatabus_20190920;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //消费者订阅消息,消费者把信息存到Map中,厂家根据Map发货
        LiveDataBus.getInstance().with("huawei",Huawei.class)
                //订阅一个观察者,系统中的代码
                .observe(this,new Observer<Huawei>() {
                    @Override
                    public void onChanged(Huawei huawei) {
                        if(huawei!=null){
                            //点击sendMessage所在的按钮,会执行这句代码
                            Toast.makeText(MainActivity.this, huawei.getType(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /**
     * 这里就是一个发布者(苹果,华为),厂家发货
     * @param view
     */
    public void sendMessage(View view) {
        //生产了一台华为手机
        Huawei huawei=new Huawei("META-20");
        //厂家发布消息,“huawei”这一字符串与消费者订阅消息的地方保持一致
        //手机发送到(淘宝的)Map中,然后在发送到订阅者(顾客)中
        LiveDataBus.getInstance().with("huawei",Huawei.class).postValue(huawei);
    }
    }

我们点击发送按钮,会根据Map中的要求将这台手机存到LiveDataBs中,然后LiveDataBus会将消息返回给订阅者。最终执行的效果就是弹出"META-20"
我们可以在任意的Activitty和任意的Fragment中发送消息,发到任意的一个位置,可以在Activity和Fragemnt通信,比EventBus方便多了,注意,它不能跨进程。
四:如第三点,也会遇到一些问题,我们现在新建一个Activity,内容与MainActivity一样,MainActivity中添加一个页面跳转的方法,

 public void startSecActivity(View view) {
        Intent intent=new Intent(this,SecActivity.class);
        startActivity(intent);
    }

我们点击MainActivity中的发送消息,然后在点击跳转按钮进入新建的Activity页面。这个时候新建页面在没有点击本界面发送消息的情况下依然会弹出"META-20"
当我们执行postValue(huawei);方法的时候,mVersion就会加一,mLastVersion>=mVersion的时候,就不会执行onChanged()。通过反射拿到两个变量的值,另他们相等,这就是我们今天的思路。

package com.example.lsn41_jetpack_livedatabus_20190920;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 这个类就是我们的总线(天猫,京东),要存放所有订阅者的信息
 */
public class LiveDataBus {
    //存放订阅者,用BusMutableLiveData存放数据
    private Map<String, BusMutableLiveData<Object>> bus;

    //单例
    private static LiveDataBus liveDataBus=new LiveDataBus();
    private LiveDataBus(){
        bus=new HashMap<>();
    }
    public static LiveDataBus getInstance(){
        return liveDataBus;
    }

    /**
     * 用来给用户进行订阅(存入map)
     * type给系统反射调用
     */
    public synchronized<T> BusMutableLiveData<T> with(String key,Class<T> type){
        if(!bus.containsKey(key)){
            bus.put(key,new BusMutableLiveData<Object>());
        }
        return (BusMutableLiveData<T>) bus.get(key);
    }

    public static class BusMutableLiveData<T> extends MutableLiveData<T>{
        @Override
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
            super.observe(owner, observer);
            hook(observer);
        }

        private void hook(Observer<? super T> observer) {
            try{
                //1.得到mLastVersion
                Class<LiveData> liveDataClass=LiveData.class;
                Field mObserversField = liveDataClass.getDeclaredField("mObservers");
                //只要不是public都要改
                mObserversField.setAccessible(true);
                //获取到这个成员变量对应的对象
                Object mObserversObject = mObserversField.get(this);
                //得到map
                Class<?> mObserversObjectClass = mObserversObject.getClass();
                //获取到mObservers对象的get方法
                Method get=mObserversObjectClass.getDeclaredMethod("get",Object.class);
                get.setAccessible(true);
                //执行get方法
                Object invokeEntry=get.invoke(mObserversObject,observer);
                //取到map中的value
                Object observerWraper=null;
                if(invokeEntry!=null && invokeEntry instanceof Map.Entry){
                    observerWraper=((Map.Entry)invokeEntry).getValue();
                }
                if(observerWraper==null){
                    throw new NullPointerException("observerWraper is null");
                }
                //得到ObserverWrapper的类对象
                Class<?> superclass=observerWraper.getClass().getSuperclass();
                Field mLastVersion = superclass.getDeclaredField("mLastVersion");
                mLastVersion.setAccessible(true);


                //2.得到mVersion
                Field mVersion = liveDataClass.getDeclaredField("mVersion");
                mVersion.setAccessible(true);

                //3.把mVersion的值填入到mLastVersion中
                Object mVersionValue=mVersion.get(this);
                mLastVersion.set(observerWraper,mVersionValue);

            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

}



    package com.example.lsn41_jetpack_livedatabus_20190920;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //消费者订阅消息
        LiveDataBus.getInstance().with("huawei",Huawei.class)
                //订阅一个观察者
                .observe(this,new Observer<Huawei>() {
                    @Override
                    public void onChanged(Huawei huawei) {
                        if(huawei!=null){
                            //点击sendMessage所在的按钮,会执行这句代码
                            Toast.makeText(MainActivity.this, huawei.getType(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /**
     * 这里就是一个发布者(苹果,华为),厂家发货
     * @param view
     */
    public void sendMessage(View view) {
        //生产了一台华为手机
        Huawei huawei=new Huawei("META-20");
        //厂家发布消息,“huawei”这一字符串与消费者订阅消息的地方保持一致
        //手机发送到(淘宝的)Map中,然后在发送到订阅者(顾客)中
        LiveDataBus.getInstance().with("huawei",Huawei.class).postValue(huawei);
    }


    public void startSecActivity(View view) {
        Intent intent=new Intent(this,SecActivity.class);
        startActivity(intent);
    }
}


    package com.example.lsn41_jetpack_livedatabus_20190920;

public class Huawei {
    public String type;

    public Huawei(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}


package com.example.lsn41_jetpack_livedatabus_20190920;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

public class SecActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //消费者订阅消息
        LiveDataBus.getInstance().with("huawei",Huawei.class).observe(
                this,
                new Observer<Huawei>() {//观查者
                    @Override
                    public void onChanged(Huawei huawei) {
                        if(huawei!=null){
                            Toast.makeText(SecActivity.this, huawei.getType(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

        );
    }
    /**
     * 发布者
     * @param view
     */
    public void sendMessage(View view){
        Huawei huawei=new Huawei("META-20");
        //厂家发布消息
        LiveDataBus.getInstance().with("huawei",Huawei.class).postValue(huawei);
    }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:onClick="sendMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发布消息"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:onClick="startSecActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

五:我们看下在Fragment中是如何通信的。

package com.example.lsn43_livedataandviewmodel;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

public class FragmentTwo extends Fragment {

    private TextView textName;
    private NameViewModel model;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two, container, false);
        textName = view.findViewById(R.id.tv_text);

        //获取viewModel
        model = ViewModelProviders.of(getActivity()).get(NameViewModel.class);
        //监听值的变化
        //model.getmCurrentName().observeForever();可以在任何时候得到数据
        model.getmCurrentName().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //更新UI
                textName.setText(s);
            }
        });
        return view;
    }
}

package com.example.lsn43_livedataandviewmodel;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

public class FragmentOne extends Fragment {

    private EditText edContent;
    private Button btnSend;
    private NameViewModel model;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        edContent = view.findViewById(R.id.et_content);
        btnSend = view.findViewById(R.id.btn_send);

        //获取viewModel
        model = ViewModelProviders.of(getActivity()).get(NameViewModel.class);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取到liveData后设置liveData的值
                model.getmCurrentName().setValue(edContent.getText().toString());
            }
        });
        return view;
    }
}


package com.example.lsn43_livedataandviewmodel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class NameViewModel extends ViewModel {

    //liveData通常和viewModel一起使用
    private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getmCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<String>();
        }
        return mCurrentName;
    }

    //如果需要可以在这里释放资源
    @Override
    protected void onCleared() {
        super.onCleared();
    }
}

Activity中有两个Fragment,上一个fragment是一个输入框和一个按钮,输入文字后单击按钮,下面的fragment会显示输入的数据,并且在屏幕旋转的时候,数据也不会丢失。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值