Search code examples
javaandroidobjectinstantiation

What does (TextView) (Button) do?


This should be an easy question for someone who knows how it works.

TextView myText = (TextView) findViewById(R.id.myText);
Button btn = (Button) findViewById(R.id.button);

What does the (Textview)/(Button) do, what is it?

Is it equivalent to

TextView myText = new TextView(findViewById(R.id.myText));
Button btn = new Button(findViewById(R.id.button));

Also, I might be mistaken, but this is in the java language not only in android?

Thanks

Note: Im not asking what a textview or a button is, im asking is this a type of instantiation, casting, etc.


Solution

  • You are initializing textview

         TextView myText = (TextView) findViewById(R.id.myText);
         // the one in the braces is casting to textview
    

    public final View findViewById (int id)

    You can findViewById of the current view hierarchy set to the activity.

    Look for a child view with the given id. If this view has the given id, return this view.

    If you want to do it programatically

         TextView myText = new TextView(ActivityName.this); 
    

    If you do as above you need to add it to the root view

    If you have LinearLayout as root view

         setContenView(R.layout.mylayout);
         LinearLayout ll = (LinearLayout) findViewById(R.id.linearlayout);   
         ll.addView(myText);  
    

    or

         setContentView(myText);