How to pass databinding object of any activity or fragment to a method parameter without needing to cast?

时间:2017-06-15 09:55:06

标签: java android android-fragments android-activity data-binding

Lets suppose I want to add a toolbar shadow effect, for that I have created a toolbarShadowEffect method being used within the activity, but this is the type of method that can be used anywhere, so it would be better for me to add this method on my baseActivity class but then the issue of databinding comes in, every activity has a unique databinding object I don't see any superclass databinding object that I can place it on a method parameter, the only solution I figured out is by using the ViewDataBinding but for that I need to cast the specific binding in order to receive the view ids within the method making it redundant, my code is below.

public void methodA(ViewDataBinding dataBinding){

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        ((ActivityMainBinding)dataBinding).customToolbar.toolbarShadowEffectId.setElevation(8);
        ((ActivityMainBinding)dataBinding).customToolbar.toolbarShadowEffectId
                .setBackgroundColor(Color.parseColor("#BDBDBD"));
    }
}

Since I need to cast the specific databinding of an activity I cannot use this method on my super class for any activity or fragment binding, I want to achieve this mechanism without the casting any help would be appreciated.

1 个答案:

答案 0 :(得分:0)

1 - 您可以声明抽象方法getToolbar()并在子活动中仅实现它。

2 - 如果工具栏始终具有相同的ID,则可以使用dataBinding.getRoot().findViewById(custom_toolbar)。但是你可能没有数据绑定就可以了。