Android官方DataBinding(五):ObservableMap,ObservableArrayMap

Android官方DataBinding(五):ObservableMap,ObservableArrayMap


写一个简单的例子说明ObservableMap,ObservableArrayMap用法。
建立一个User.java的数据模型:
package zhangphil.test;

import android.databinding.BaseObservable;
import android.databinding.ObservableArrayMap;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.databinding.ObservableMap;

/**
 * Created by Phil on 2017/8/17.
 */

public class User extends BaseObservable {
    public final ObservableInt id = new ObservableInt();
    public final ObservableField name = new ObservableField<>();
    public final ObservableMap quality = new ObservableArrayMap<>();
    public final ObservableField current = new ObservableField<>();
}



Keys.java:

package zhangphil.test;

/**
 * Created by Phil on 2017/8/18.
 */

public class Keys {
    public static final String current = "current_value";
}





activity_main.xml布局:



    
        
        
        

        
    

    

        


MainActivity.java:
package zhangphil.test;

import android.databinding.DataBindingUtil;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import zhangphil.test.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

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

        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        final User user = new User();
        binding.setUser(user);

        user.id.set(0);
        user.name.set("zhangphil");

        user.quality.put("normal", "N url");
        user.quality.put("high", "H url");
        user.quality.put("super", "S url");

        user.current.set("normal");

        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                user.id.set(1);
                user.quality.put("high", "new H url");
                user.current.set("high");
            }
        });
    }
}



代码运行结果,初始化状态:
Android官方DataBinding(五):ObservableMap,ObservableArrayMap_第1张图片





点击更新按钮:
Android官方DataBinding(五):ObservableMap,ObservableArrayMap_第2张图片




附录:
1,《Android官方DataBinding简例(一)》链接:http://blog.csdn.net/zhangphil/article/details/77322530    
2,《Android官方DataBinding(二):动态数据更新notifyPropertyChanged》链接:http://blog.csdn.net/zhangphil/article/details/77328688   
3,《Android官方DataBinding(三):RecyclerView 使用ViewDataBinding更新数据》链接:http://blog.csdn.net/zhangphil/article/details/77367432  
4,《Android官方DataBinding(四):BindingAdapter》链接:http://blog.csdn.net/zhangphil/article/details/77374211 

你可能感兴趣的:(Android,Android,android)