Android Layouts XML & / or Programatically
Can these be defined via XML and Programatically or are they mutually exc开发者_运维技巧lusive? I haven't seen any combined tutorials so am wondering if that is the answer.
Yeah, it's really the same thing -- using XML is typically easier to maintain, plus you can see a preview of it before compiling. It's also easier to see the layout structure, that sort of thing. However, most, if not anything you can do in XML, you can do in code. Definitely not the case in reverse.
Here's an example of doing the same thing with both Java and XML:
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Testing!"
/>
TextView textView = new TextView(this);
textView.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.setText("Testing!");
Basically, I'd advise using XML for layouts any time you can, unless it's something that needs to be modified during runtime, or is something that can't be achieved using XML alone.
Yes. You can load a layout from XML, and then add View objects to the layout programmatically. You can also create a layout programmatically, and then add views taken from XML (look at the LayoutInflater: http://developer.android.com/reference/android/view/LayoutInflater.html).
Views and layouts can be specified both ways:
setContentView(R.layout.main);
mylayout.addView(myButton);
精彩评论