There are two ways to create Layout.
public final class R {
public static final class id {
public static final int mytxt=0x7f050044;
}
}
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView myTxtView = new TextView(this);
EditText myEdtText = new EditText(this);
myTxtView.setText(“Enter Text”);
myEdtText.setText(“Write Text Here!”);
int lHeight = LinearLayout.LayoutParams.MATCH_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
ll.addView(myTxtView, new LinearLayout.LayoutParams(lHeight, lWidth));
ll.addView(myEdtText, new LinearLayout.LayoutParams(lHeight, lWidth));
setContentView(ll);
} }
- Layouts in XML
- Layouts in Code
1. Layouts in XML
Example: main.xml(Layout file)
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
<TextView android:id=”@+id/mytxt”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/Write here..” />
</LinearLayout>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent” >
<TextView android:id=”@+id/mytxt”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/Write here..” />
</LinearLayout>
- It's a preferred way of implementing your user interfaces (UIs) or defining your UI in XML.
- As it decouples your application logic from your UI design.
- Keeping the visual design decoupled from the application code, helps keep the code concise.
- To get access to the UI elements we have to add identifier(id) attributes to them in the XML definition.
- The above line generates an id named "mytxt" for TextView,which are stored in /gen/packageName/R.java of your poject hierarchy.
public final class R {
public static final class id {
public static final int mytxt=0x7f050044;
}
}
2. Layouts in Code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView myTxtView = new TextView(this);
EditText myEdtText = new EditText(this);
myTxtView.setText(“Enter Text”);
myEdtText.setText(“Write Text Here!”);
int lHeight = LinearLayout.LayoutParams.MATCH_PARENT;
int lWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
ll.addView(myTxtView, new LinearLayout.LayoutParams(lHeight, lWidth));
ll.addView(myEdtText, new LinearLayout.LayoutParams(lHeight, lWidth));
setContentView(ll);
} }
Comments
Post a Comment