2016-10-16 3 views
-1

私のレイアウトでfindViewByIdを呼び出すと、そのビューが宣言されている型 "ScrollView"の代わりにジェネリック型 "View"が返されているのが分かります。として。Android:findViewById戻り値の型はScrollViewではなくViewです

私のXMLファイルでは、idが "scrollview"のビューがとして明示されていますが、この要素のfindViewByIdはScrollViewではなくViewを返します。なぜこうなった?

注:このxmlレイアウトの親コンテナは断片ですが、これが変更されるかどうかはわかりません。

@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> 

答えて

1

findViewByIdリターンView。あなたは

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

ありがとうございました。これが解決策です。 – Cody

2

変更mScrollview = v.findViewById(R.id.scrollview);

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

にFindViewByIdしたがってuは、特定の型にキャストするために必要なすべてのUI要素のスーパークラスである Viewを返し、次のように ScrollViewにそれを castする必要があります。

1

あなたが例えばのために表示するレイアウトやウィジェットをキャストする必要がフラグメントの場合には、必ず

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

をキャストしてください。また、mscroll =(Scrollview)yourview.findviewbyid(R.id.scroll)とIこれを見てみてください。 findViewById in Fragment

関連する問題