2014-09-03 25 views
1

在Asyntask中,我想更改textswitcher文本,如果我添加新視圖,應用程序崩潰。 代碼示例:不能向視圖查看器添加2個以上的視圖

   textSwitcher.setInAnimation(MainActivity.this,android.R.anim.slide_in_left); 
      textSwitcher.setOutAnimation(MainActivity.this, android.R.anim.slide_out_right); 
      TextView tv=new TextView(MainActivity.this); 
      tv.setGravity(Gravity.CENTER | Gravity.LEFT); 
      tv.setTypeface(custom_font); 
      tv.setTextColor(Color.parseColor("#00285E")); 
      textSwitcher.addView(tv); 

最後一行給出了錯誤之後,我決定刪除所有的意見,我加入textSwitcher.removeAllViews();,那麼它給空指針。你認爲解決什麼問題?

+0

你會得到哪個錯誤?你能在這裏製作嗎? – cyanide 2014-09-03 22:27:33

+0

無法添加超過2個視圖到視頻切換器錯誤 – Ozan 2014-09-03 22:28:56

+0

發佈整個班級 – 2014-09-04 01:16:39

回答

0

ViewSwitcher只能有兩個孩子,就像它在該類的documentation上所說的那樣。我個人還沒有見過使用ViewSwitcher的人,這是一個老班,現在你可以用ObjectAnimators自己獲得相同或更好的效果。

您可以創建自己的ViewGroup,讓您切換任何其他視圖。如果是我,我也只是延長FrameLayout和簡單的添加是這樣的:

public void switchView(View view) { 
    // add the new view and reveal 
    view.setAlpha(0); 
    addView(view); 
    view.animate().alpha(1f).start(); 

    if (getChildCount() > 0) { 
     // simultaneously remove the previous view 
     final View child = getChildAt(0); 
     child.animate().alpha(0).setListener(new AnimatorListenerAdapter() { 
      @Override 
      public void onAnimationEnd(Animator animator) { 
       // remove the child when the animation ends 
       removeView(child); 
      } 
     }).start(); 
    } 
} 
0

這完全是任意的行爲。您可以覆蓋類似ViewSwitcher類的ViewAnimator,並用可變子視圖計數替換0/1處理。真的很簡單!