androidandroid-linearlayoutviewanimator

Android: why nothing shows up on screen?


and thanks for your help. I am trying to use a ViewAnimator tho show different views on screen.

So:

But nothing shows on screen...

public class MainActivity extends Activity {
public DataBaseHelper db;
public EditText enter;
public TextView tv;
public ArrayList<String> listWord;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ViewAnimator viewAnimator = new  ViewAnimator(this);

    LayoutInflater inflater = (LayoutInflater)this.getSystemService
              (Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout front =(LinearLayout) inflater.inflate(R.layout.front,viewAnimator );
    LinearLayout back =(LinearLayout) inflater.inflate(R.layout.back,viewAnimator );

    viewAnimator.addView(front);
    viewAnimator.addView(back);

    setContentView(viewAnimator);
    viewAnimator.showNext();

Any help very much appreciated!


Solution

  • The problem is in the following lines:

    LinearLayout front =(LinearLayout) inflater.inflate(R.layout.front,viewAnimator);
    LinearLayout back =(LinearLayout) inflater.inflate(R.layout.back,viewAnimator);
    

    because when you provide viewAnimator as root view during inflation, then the same root view is returned, and in your code causing the ClassCastException because ViewAnimator cannot be cast'ed into LinearLayout.

    For your reference:

    public View inflate (int resource, ViewGroup root)

    Parameters

    resource ID for an XML layout resource to load (e.g., R.layout.main_page)

    root Optional view to be the parent of the generated hierarchy.

    Returns

    The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.

    Simply provide null as root view and it work just fine. For example:

    LinearLayout front = (LinearLayout) inflater.inflate(R.layout.front, null);
    LinearLayout back = (LinearLayout) inflater.inflate(R.layout.back, null);