0

example을 사용하여 내 앱에서 CollapsingToolbarLayout의 '부제목'을 설정하려고합니다.CollapsingToolbarLayout의 자막을 설정하는 중 'java.lang.ClassCastException'받기

CollapsingToolbarLayout collapsingToolbarLayout; 
    Toolbar toolbar; 
    HeaderView toolbarHeaderView; 
    HeaderView floatHeaderView; 

    collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar); 

    // error on the line below 
    toolbarHeaderView = (HeaderView) findViewById(R.id.toolbar_header_view); 
    floatHeaderView = (HeaderView) findViewById(R.id.float_header_view); 

    toolbarHeaderView.bindTo("title", "subtitle"); 
    floatHeaderView.bindTo("title", "subtitle"); 

여기 activity_main.xml입니다 :

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 
    android:id="@+id/coordinatorLayout" 
    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" 
    android:fitsSystemWindows="true" 
    tools:context="com.abc.zzz.Profile"> 

    <android.support.design.widget.AppBarLayout 
     android:id="@+id/appBarLayout" 
     android:layout_width="match_parent" 
     android:layout_height="256dp" 
     android:theme="@style/AppTheme.AppBarOverlay" 
     android:fitsSystemWindows="true"> 

     <android.support.design.widget.CollapsingToolbarLayout 
      android:id="@+id/collapse_toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      app:layout_scrollFlags="scroll|exitUntilCollapsed" 
      app:contentScrim="@color/colorPrimary" 
      android:fitsSystemWindows="true" 
      app:popupTheme="@style/AppTheme.PopupOverlay"> 

      <android.support.v7.widget.Toolbar 
       android:id="@+id/toolbar" 
       android:layout_width="match_parent" 
       android:layout_height="?attr/actionBarSize" 
       app:layout_collapseMode="parallax"> 

       <include 
        android:id="@+id/toolbar_header_view" 
        layout="@layout/header_view" 
        android:layout_height="wrap_content" 
        android:layout_width="match_parent" 
        android:layout_marginRight="@dimen/header_view_end_margin_right" 
        android:layout_marginEnd="@dimen/header_view_end_margin_right" 
        android:visibility="gone" 
        /> 

      </android.support.v7.widget.Toolbar> 

     </android.support.design.widget.CollapsingToolbarLayout> 

    </android.support.design.widget.AppBarLayout> 

    <include 
     android:id="@+id/float_header_view" 
     layout="@layout/header_view" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     app:layout_behavior="com.abc.zzz.ViewBehavior"/> 

</android.support.design.widget.CoordinatorLayout> 

여기 header_view.xml입니다 :

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

    <!-- Title --> 
    <TextView 
     android:id="@+id/header_view_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/white" 
     android:textSize="18sp" 
     /> 

    <!-- Subtitle --> 
    <TextView 
     android:id="@+id/header_view_sub_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/white" 
     android:textSize="16sp" 
     /> 

</LinearLayout> 

여기 HeaderView.java입니다 : 여기

onCreate()에서 Profile.java의 코드입니다

public class HeaderView extends LinearLayout { 

    TextView title; 

    TextView subTitle; 

    public HeaderView(Context context) { 
     super(context); 
    } 

    public HeaderView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public HeaderView(Context context, AttributeSet attrs, int defStyleAttr) { 
     super(context, attrs, defStyleAttr); 
    } 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public HeaderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 
     super(context, attrs, defStyleAttr, defStyleRes); 
    } 


    @Override 
    protected void onFinishInflate() { 
     super.onFinishInflate(); 
     title = (TextView) findViewById(R.id.header_view_title); 
     subTitle = (TextView) findViewById(R.id.header_view_sub_title); 
    } 

    public void bindTo(String title) { 
     bindTo(title, ""); 
    } 

    public void bindTo(String title, String subTitle) { 
     hideOrSetText(this.title, title); 
     hideOrSetText(this.subTitle, subTitle); 
    } 

    private void hideOrSetText(TextView tv, String text) { 
     if (text == null || text.equals("")) 
      tv.setVisibility(GONE); 
     else 
      tv.setText(text); 
    } 
} 

여기 ViewBehavior.java입니다 : 위에서 지정한 라인에 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.zzz/com.abc.zzz.Profile}: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to com.abc.zzz.HeaderView :

public class ViewBehavior extends CoordinatorLayout.Behavior<HeaderView> { 

    private Context mContext; 

    private int mStartMarginLeft; 
    private int mEndMargintLeft; 
    private int mMarginRight; 
    private int mStartMarginBottom; 
    private boolean isHide; 

    public ViewBehavior(Context context, AttributeSet attrs) { 
     mContext = context; 
    } 

    @Override 
    public boolean layoutDependsOn(CoordinatorLayout parent, HeaderView child, View dependency) { 
     return dependency instanceof AppBarLayout; 
    } 

    @Override 
    public boolean onDependentViewChanged(CoordinatorLayout parent, HeaderView child, View dependency) { 
     shouldInitProperties(child, dependency); 

     int maxScroll = ((AppBarLayout) dependency).getTotalScrollRange(); 
     float percentage = Math.abs(dependency.getY())/(float) maxScroll; 

     float childPosition = dependency.getHeight() 
       + dependency.getY() 
       - child.getHeight() 
       - (getToolbarHeight() - child.getHeight()) * percentage/2; 


     childPosition = childPosition - mStartMarginBottom * (1f - percentage); 

     CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams(); 
     lp.leftMargin = (int) (percentage * mEndMargintLeft) + mStartMarginLeft; 
     lp.rightMargin = mMarginRight; 
     child.setLayoutParams(lp); 

     child.setY(childPosition); 

     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 
      if (isHide && percentage < 1) { 
       child.setVisibility(View.VISIBLE); 
       isHide = false; 
      } else if (!isHide && percentage == 1) { 
       child.setVisibility(View.GONE); 
       isHide = true; 
      } 
     } 
     return true; 
    } 

    private void shouldInitProperties(HeaderView child, View dependency) { 

     if (mStartMarginLeft == 0) 
      mStartMarginLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.header_view_start_margin_left); 

     if (mEndMargintLeft == 0) 
      mEndMargintLeft = mContext.getResources().getDimensionPixelOffset(R.dimen.header_view_end_margin_left); 

     if (mStartMarginBottom == 0) 
      mStartMarginBottom = mContext.getResources().getDimensionPixelOffset(R.dimen.header_view_start_margin_bottom); 

     if (mMarginRight == 0) 
      mMarginRight = mContext.getResources().getDimensionPixelOffset(R.dimen.header_view_end_margin_right); 

    } 


    public int getToolbarHeight() { 
     int result = 0; 
     TypedValue tv = new TypedValue(); 
     if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { 
      result = TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics()); 
     } 
     return result; 
    } 

} 

문제 내가이 오류를 얻고 있다는 것입니다.

왜 내가이 오류가 발생하고 으로 해결할 수 있습니까?

알려 주시기 바랍니다.

답변

2

코드에 표시되지 않았지만 header_view.xmlLinearLayout이 루트보기로 표시되어 있습니다.

그래서 기본적으로 발생하는 경우 : <include 코드가 header_view.xml의 루트에 LinearLayout으로 "대체됩니다"한 다음 반환 findViewById(R.id.toolbar_header_view)를 호출하는 LinearLayout 다음과 (HeaderView)이이 HeaderView 인 VM을 이야기하고, 그러나 그것은 LinearLayout입니다. 그래서 그것은 부서진다!

당신이 그것을 보여주지 않았다 코드의 조각을 보지 않고 최선의 선택은 다음 중 하나입니다

  1. header_view.xml의 루트에 <HeaderView>을 넣어,

또는 가능하지 않은 경우 더 많은 물건이 header_view.xml

내부에 존재이기 때문에 나는 내에서 다음 include을 찾을 수
  • 변화 코드를
      을하고 실제 HeaderView를 찾으려면 nclude를 입력하십시오. 같은

    뭔가 : 그것은 findViewById 두 번 호출하는

    toolbarHeaderView = (HeaderView) findViewById(R.id.toolbar_header_view).findViewById(R.id.header_view_id); 
    floatHeaderView = (HeaderView) findViewById(R.id.float_header_view).findViewById(R.id.header_view_id); 
    

    참고. 하나는 포함 용이고 다른 하나는 HeaderView 용입니다.