سؤال

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.

هل كانت مفيدة؟

المحلول

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); 

نصائح أخرى

Well, the (Type) like (Button) or (TextView) is called a cast. You can easily find any information about casts in any language on Google.

Android is a platform, Java is the language used to write Android applications. So

TextView myText = (TextView) findViewById(R.id.myText);

is a cast (View -> TextView) in java and no, it isn't equivalent to use a constructor.

View.findViewById()

Returns View type, this View type could be TextView, Button or something else. By doing cast (Which is what () means), you are telling runtime that returned View is of type whatever in those braces.

TextView and Button are subclasses of View type.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top