Espresso test for Horizontal Scroll View - android

I have following HorizontalScrollView which I add items to it programmatically:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="vm"
type="com.sample.android.tmdb.ui.detail.MovieDetailViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:visibleGone="#{vm.isTrailersVisible}">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trailers"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<HorizontalScrollView
android:id="#+id/trailer_scroll_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:items="#{vm.trailers}" />
</HorizontalScrollView>
</LinearLayout>
</layout>
And here I add items to it :
#JvmStatic
#BindingAdapter("items")
fun addItems(linearLayout: LinearLayout, trailers: List<Video>) {
linearLayout.removeAllViews()
val context = linearLayout.context
for (trailer in trailers) {
val thumbContainer = context.layoutInflater.inflate(R.layout.video, linearLayout, false)
val thumbView = thumbContainer.findViewById<ImageView>(R.id.video_thumb)
thumbView.apply {
setOnClickListener {
val playVideoIntent = Intent(Intent.ACTION_VIEW, Uri.parse(Video.getUrl(trailer)))
context.startActivity(playVideoIntent)
}
}
linearLayout.addView(thumbContainer)
}
}
Now I want to add a Espresso test for it. I want to scroll HorizontalScrollView and click on third item. Until now I wrote following test:
#Test
fun shouldBeAbleToDisplayTrailer() {
onView(withId(R.id.list)).perform(RecyclerViewActions
.actionOnItemAtPosition<MovieViewHolder>(8, click()))
onView(withId(R.id.trailer_scroll_view)).perform(nestedScrollTo()).check(matches(isDisplayed()))
// intended(Matcher<Intent> matcher) asserts the given matcher matches one and only one
// intent sent by the application.
//intended(allOf(hasAction(Intent.ACTION_VIEW)))
}
But I do not know, how to scroll HorizontalScrollView. Can you please help?

The answer is just two clicks away:
Check scrollTo() View Action implementation:
public static ViewAction scrollTo() {
return actionWithAssertions(new ScrollToAction());
}
Check ScrollToAction() implementation:
/** Enables scrolling to the given view. View must be a descendant of a ScrollView or ListView. */
The view should fulfil below constraints to apply ScrollToAction() to it. I agree that ScrollToAction() description can be improved a bit:
withEffectiveVisibility(Visibility.VISIBLE),
isDescendantOfA(
anyOf(
isAssignableFrom(ScrollView.class),
isAssignableFrom(HorizontalScrollView.class),
isAssignableFrom(ListView.class))));
And the answer is - use ViewActions.scrollTo() to scroll HorizontalScrollView.

Related

ViewPager child to swipe next the parent

I have a ViewPager2 which I'm using with a RecyclerView Adapter. I'm binding the children of each viewpager item via the ViewHolder and everything is working okay.
I have a bunch of elements in this ViewPager item XML, some RadioButton components and a Button. I want this button to move it to the next item.
I know how to do that externally, assigning a sibling to the ViewPager2 and then setting a click-listener in the activity and then comparing currentItem of the ViewPager with the adapter's total item count.
I want the "Move to next" button inside the ViewPager as I want to change it based on the inputs supplied to the RadioButton components.
I'm currently stuck at failing getting the ViewPager item's button in the activity to set the click-listener. Is there any workaround to get the child element via the adapter itself?
Here's the activity_quiz.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".ui.quiz.view.QuizActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/quiz_list"
android:layout_width="match_parent"
android:layout_height="600dp"
android:clipToPadding="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="16dp"
tools:listitem="#layout/quiz_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
The quiz_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
android:padding="#dimen/bigSpacing"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/question"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/choices">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/choice_1"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/choice_2"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/choice_3"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/choice_4"/>
</RadioGroup>
<Button
android:id="#+id/result_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Next question" />
</LinearLayout>
The MyAdapter class (kotlin)
class MyAdapter: RecyclerView.Adapter<MyAdapter.MyViewHolder> {
override fun onCreateViewHolder(...) {
...
}
override fun getItemCount(): Int {
...
}
override fun onBindViewHolder(...) {
...
}
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
fun bind(someData: SomeData) {
itemView.question.text = somedata.question
itemView.choice_1.text = somedata.choice_1
itemView.choice_2.text = somedata.choice_2
itemView.choice_3.text = somedata.choice_3
itemView.choice_4.text = somedata.choice_4
val answerKey = someData.answerKey
var rightOrWrong = ""
itemView.choices.setOnCheckedChangeListener {_, checkedID ->
val checkedIndex: Int = itemView.choices.indexOfChild(itemView.choices.findViewById(checkedID))
if(checkedIndex + 1 == answerKey.toInt()) {
rightOrWrong = "Correct! Next Question."
} else {
rightOrWrong = "Incorrect :/ Next Question."
}
itemView.result_button.text = rightOrWrong
}
}
}
And the QuizActivity.kt file
class QuizActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz)
val myAdapter = MyAdapter()
quiz_list.adapter = myAdapter
// quiz_list.result_button.setOnClickListener {
// No idea how to get the children correctly, as this one throws errors
// }
}
}
First, why do you want to use RecyclerView.Adapter<MyAdapter.MyViewHolder> as an adapter for viewpager2? There is FragmentStateAdapter a built-in class implementation of PagerAdapter that uses a Fragment to manage each page, which is recommended for viewpager2.
Second, you are not inflating the views in MyViewHolder, I don't know if you left them intentionally for this post.
You cant access child views like this quiz_list.result_button.setOnClickListener {} while using something like RecyclerView, Viewpagger. You can access them in the ViewHolder after you inflate them, you can set any listener there aswell

Why the recycler view test is not passed?

I've written the test, testing if the recycler view is displayed (id: comments_view), but it always fails and I've no idea why. When I'm checking for layout (id: cm), the test passes.
I have the following fragment code:
<layout 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">
<data>
<variable
name="post"
type="com.example.kotlinpostapi.apiObjects.Post" />
<variable
name="comments"
type="java.util.List" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".views.MainActivity"
android:id="#+id/cm">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/comments_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
The test code (I'm navigating to the fragment from another one):
#RunWith(AndroidJUnit4::class)
class CommentsListTest{
#get: Rule
val activityScenario = ActivityScenarioRule(MainActivity::class.java)
#Test
fun testCommentsAreDisplayed() {
onView(withId(R.id.posts_view)).perform(actionOnItemAtPosition<PostAdapter.PostsViewHolder>(0, MyMatchers.clickChildView(R.id.show_comments_button)))
//it fails
onView(withId(R.id.comments_view)).check(matches(isDisplayed()))
//it passes
onView(withId(R.id.cm)).check(matches(isDisplayed()))
}
}
How is it possible, and how can I test my recycler view?
The height of the RecyclerView is set to wrap_content and if the element is not visible at least 90% the test fails.
What you could do is to check one of the RecyclerView children.
I firstly declare the following method:
fun nthChildOf(parentMatcher: Matcher<View?>, childPosition: Int): Matcher<View?>? {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("with $childPosition child view of type parentMatcher")
}
override fun matchesSafely(view: View): Boolean {
if (view.parent !is ViewGroup) {
return parentMatcher.matches(view.parent)
}
val group = view.parent as ViewGroup
return parentMatcher.matches(view.parent) && group.getChildAt(childPosition) == view
}
}
}
with this you can check whether its first child is displayed:
onView(nthChildOf(withId(R.id.comments_view), 0)).check(matches(isDisplayed()))
And to check one element of its children (recyclerview_element_id for example):
onView(allOf(
withId(R.id.recyclerview_element_id),
isDescendantOfA(
nthChildOf(withId(R.id.comments_view), 0))
)).check(matches(isDisplayed()))
Another thing you could try if your RecyclerView expands to the available space of the screen is to change the layout of the RecyclerView to have all the constraints set and with and height to 0dp:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/comments_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
I have it this way and doing:
onView(withId(R.id.myRecyclerviewId)).check(matches(isDisplayed()))
works for me.

Why my foreach breaks when I try to draw dynamic buttons in Kotlin?

I need to draw dynamic buttons inside a foreach loop that retrieve data from my anko sqlite, the foreach only enter once and breaks and only draw one button in my layout, what I doing wrong? my code is this:
fun loadZones (ctx: Context, update: String, view: View, layout: LinearLayout) {
val zonesParser = rowParser{idzone: Int, zone: String -> Pair(idzone, zone)}
for (it in ctx.database.use {
select("tableplan")
.distinct()
.column("idzone")
.column("zone")
.orderBy("zone")
.parseList(zonesParser)
}) {
val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val btnZone = layoutInflater.inflate(R.layout.zones_item, null) as MaterialButton
btnZone.text = it.second
btnZone.id = it.first
layout.addView(btnZone, layoutParams)
Log.e("PAIR", "FIN DEL CICLO")
continue
}
}
The data that retrieves from my query is this:
(2, LARRY)
(1, MADISON)
That's my activity, I need to draw the buttons in "lytZonesButtons" id
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".TablePlanFragment">
<com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent"
android:layout_height="wrap_content" android:elevation="2dp"
tools:targetApi="lollipop" app:liftOnScroll="true">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbarTablePlan"
style="#style/com.madison.Toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="#string/table_title_module">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_marginTop="56dp"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:orientation="horizontal"
android:background="#color/orangeLighter"
android:gravity="center_vertical"
android:padding="5dp" android:id="#+id/lytZonesButtons" />
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="112dp"
android:padding="5dp">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rc_tableplan"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</androidx.core.widget.NestedScrollView>
</FrameLayout>
and that's my button template that I called "zones_item":
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.button.MaterialButton
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" style="#style/com.madison.AppButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.MaterialComponents.Subtitle2"
tools:text="MADISON"
tools:targetApi="lollipop"
android:layout_margin="5dp"
/>
EDIT: I found the solution!
I don't now why my layout instance in the twice iteration of my loop throws NullPointerException but not shows in the log cat, my solution was put the loop code in onCreateView function, this is the code:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.activity_tableplan, container, false)
val iActivity = (activity as AppCompatActivity)
iActivity.setSupportActionBar(view.toolbarTablePlan)
iActivity.supportActionBar?.setDisplayShowTitleEnabled(true)
// view.rc_tableplan.setHasFixedSize(true)
// val gridLayoutManager = GridLayoutManager(context, 2, GridLayoutManager.HORIZONTAL, false)
// view.rc_tableplan.layoutManager = gridLayoutManager
val response = loadTablePlan(this.context!!, "no")
if (response.trim().toUpperCase() == "SUCCESS") {
val zonesParser = rowParser{idzone: Int, zone: String -> Pair(idzone, zone)}
for (zone in this.context!!.database.use {
select("tableplan")
.distinct()
.column("idzone")
.column("zone")
.orderBy("zone")
.parseList(zonesParser)
}) {
val layout:LinearLayout = view.lytZonesButtons
layout.let {
val btnZone = layoutInflater.inflate(R.layout.zones_item, layout, false) as MaterialButton
btnZone.text = zone.second
btnZone.id = zone.first
btnZone.requestLayout()
layout.addView(btnZone)
Log.e("PAIR", "FIN DEL CICLO")
}
}
}
return view
}
Thanks a lot for all people that tried help me, some admin can close my question please.
The hint is only one button is showing. Your trying to inflate the same view twice in the same spot.
You need to add an empty linearlayout in your xml. And in your loop change the buttonz..
var btnZone = findViewById(R.layout.btnZone)
button.text = "Pair"
btnZone.addView(button, layoutParams)
That's not the exact code (and probably not even the right syntax) but it shows you how you need to modify your loop.
Basicly you were attempting to inflate the same instance of the same view. When really your not inflating any views this way your just adding views.
Note
If you have a linearlayout in your xml when you add another button view to it it will add it below it. If you set the layout orientation to horizontal the button view then gets added beside the other one.
here's a link to an example.
Sorry I would make sure my code matched your code and variables with proper syntax but I am at work.

How to write an espresso test case for a fragment container with recyclerview click item action

I have an activity which has a fragment container which loads a fragment with recyclerview. On clicking any of the recycler view items, it will open a new activity. I want to write an espresso test case for this scenario.
My Activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/background">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_weight="1">
</FrameLayout>
My Fragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_items"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MyTestCase:
#RunWith(AndroidJUnit4.class)
public class MainActivityTest {
#Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
#Before
public void init() {
mActivityTestRule.getActivity()
.getSupportFragmentManager().beginTransaction();
}
#Test
public void recyclerview_clickTest() {
/* onView(withId(R.id.fragmentContainer)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
onView(withText("Alpha")).perform(click());
onView(allOf(instanceOf(TextView.class), withParent(withResourceName("action_bar"))))
.check(matches(withText("Alpha")));*/
onData(allOf(is(new BoundedMatcher<Object, MyModel>(MyModel.class) {
#Override
public void describeTo(Description description) {
}
#Override
protected boolean matchesSafely(MyModel abc) {
return onView(allOf(instanceOf(TextView.class), withParent(withResourceName("action_bar"))))
.check(matchesSafely(withResourceName(abc)));
}
})));
}
}
TIA.
You can use ViewMatchers for this action
Example
onView(withId(R.id.your_recycler_view)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
Try the following
onView(allOf(isDisplayed(), withId(R.id.your_recycler_view))).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
If the above still does not work and you're sure that the recycler view is on display then launch UIAutomator and try to highlight above your recycler view, check if the thing it highlights is your recycler view, chances are your recycler view might have something on top of it which makes it not clickable (or it might not even be on display).
Another thing to check is if there is a transition and no animation is in place, the test might be looking for your recycler view while it is not yet on display. You might want to check on https://developer.android.com/training/testing/espresso/idling-resource
For a quicker check, just make the thread sleep prior to clicking on the recycler view
Thread.sleep(timeMs, timeout)

MVVM BindingAdapters not showing ProgressBar

I'm trying to create a simple example with databinding and BindingAdapters in order to show/hide a ProgressBar depending on TextView if it's empty or not. Below you can see my code. What I'm doing wrong?
loading_state.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="textString"
type="String"/>
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:visibleGone="#{textString==null}">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{textString}"/>
</android.support.constraint.ConstraintLayout>
</layout>
My BindingAdapter
object BindingAdapters {
#JvmStatic
#BindingAdapter("visibleGone")
fun showHide(view: View, visible: Boolean){
view.visibility = if (visible) View.VISIBLE else View.GONE
}
}
I include the layout in my second fragment in order to check the textview text
<include layout="#layout/loading_state"
app:textString="#{textView2.text.toString()}"/>
and also in my SecondFramgent class I take the value from MainFragment class (I'm using the new Navigation component)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val txtFromMain = SecondFragmentArgs.fromBundle(arguments)
textView2.text = txtFromMain.txtFromMain
}
What am I missing?
Thank you very much.
For those facing the same issue you can find my solutions matches in my case below:
I had to change my BindingAdapter.
#BindingAdapter("visibleGone")
fun showHide(view: View, visible: String){
view.visibility = if (visible.isEmpty()) View.VISIBLE else View.GONE
}
You did not set two-way databinding for TV, thus string is not getting updated inside databinding
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{textString}"/>
Change android:text="#{textString}" to android:text="#={textString}"
This is first look of the problem, does it help?

Categories

Resources