Skip to content
This repository has been archived by the owner on Nov 14, 2018. It is now read-only.

Add the ability to get the parent Activity of a View #593

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

gahfy
Copy link

@gahfy gahfy commented Jul 8, 2018

Adding the ability to get the parent Activity of a View.

@googlebot
Copy link

Thanks for your pull request. It looks like this may be your first contribution to a Google open source project (if not, look below for help). Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

📝 Please visit https://cla.developers.google.com/ to sign.

Once you've signed (or fixed any issues), please reply here (e.g. I signed it!) and we'll verify it.


What to do if you already signed the CLA

Individual signers
Corporate signers

@gahfy
Copy link
Author

gahfy commented Jul 8, 2018

I signed it!

@googlebot
Copy link

CLAs look good, thanks!

@gahfy
Copy link
Author

gahfy commented Jul 8, 2018

Need #582 to be merged otherwise CI won't pass

@JakeWharton
Copy link
Contributor

Why do you need this? Accessing the activity from a view is a generally discouraged pattern as it creates a bad coupling that prevents reuse.

@gahfy
Copy link
Author

gahfy commented Jul 10, 2018

@JakeWharton Most of the time, I use it in BindingAdapters in order to put the Observer process out of the Activity to avoid boilerplate code in Activity which is often the same. For example:

/**
 * Sets a mutable visibility to the View. When the value of the LiveData changes, the visibility of
 * the View will change as well.
 * @param view the View to which to set the mutableVisibility
 * @param visibility the visibility LiveData the View should observe
 */
@BindingAdapter("mutableVisibility")
fun setMutableVisibility(view: View, visibility: MutableLiveData<Int>?) {
    val parentActivity: AppCompatActivity? = view.getParentActivity()
    if(parentActivity != null && visibility != null) {
        visibility.observe(parentActivity, Observer { value -> view.visibility = value?: View.VISIBLE})
    }
}

Then all you have to do is to set app:mutableVisibility as attribute in XML, and you don't have to care about Observers in your Kotlin Activity.

@gahfy gahfy force-pushed the master branch 3 times, most recently from b371ca8 to adea039 Compare July 16, 2018 15:50
@gahfy
Copy link
Author

gahfy commented Jul 16, 2018

Rebased on #582 as it has been merged to let CI pass

@gahfy
Copy link
Author

gahfy commented Jul 22, 2018

Does someone understand the error of instrumented tests and how to solve it?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants