Cody Cody - 1 month ago 11
Java Question

Android: findViewById return type is View instead of ScrollView

I'm trying to figure out why my call to findViewById on my layout is returning the generic type "View" instead of the type "ScrollView" that the view in question is declared as.

If you look below, my xml file clearly lists the view with id "scrollview" as a , yet findViewById on this element only returns a View, not a ScrollView. Why is this happening?

Note: the parent container to this xml layout is a Fragment, not sure if this changes things.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.menu_fragment_capo, container, false);

mScrollview = v.findViewById(R.id.scrollview); //ERROR HERE
mScrollview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//mScrollview.smoothScrollTo();
return true; //true = not scrollable
}
});
}


scroller_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/buttonLayoutParent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>

Answer

findViewById return a View. You need to cast it to a ScrollView as follows,

mScrollview = (ScrollView) v.findViewById(R.id.scrollview);
Comments