1.) Create a new project by File-> New -> Android Project name it InflateUIView.
2.) Write following into main.xml:
1
2
3
4
5
6
7
8
| <?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" android:id= "@+id/layout1" > </LinearLayout> |
3.) Create and write following into layout/buttons.xml:
1
2
3
4
5
6
7
8
| <?xml version= "1.0" encoding= "utf-8" ?> <Button xmlns:android= "http://schemas.android.com/apk/res/android" android:id= "@+id/button_small_left" style= "?android:attr/buttonStyleSmall" android:text= "Press to close" android:layout_width= "wrap_content" android:layout_height= "wrap_content" /> |
4.) Create and write following into layout/text.xml:
1
2
3
4
5
6
7
| <?xml version= "1.0" encoding= "utf-8" ?> android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "@string/dynamic_text" ></TextView> |
5.) Run for output.
Steps:
1.) Create a project named InflateUIView and set the information as stated in the image.
Build Target: Android 4.2
Application Name: InflateUIView
Package Name: com. example. InflateUIView
Activity Name: InflateUIView
Min SDK Version: 4.2
Application Name: InflateUIView
Package Name: com. example. InflateUIView
Activity Name: InflateUIView
Min SDK Version: 4.2
2.) Open InflateUIView.java file and write following code there:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| package com.example.inflateview; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class InflateView extends Activity { LinearLayout lLayout; float [] orientation; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.main); final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); Button b = (Button)inflater.inflate(R.layout.buttons, null ); lLayout = (LinearLayout)findViewById(R.id.layout1); lLayout.addView(b); b.setOnClickListener( new OnClickListener() { public void onClick(View v) { //restrict to adding only 1 textview child element if (lLayout.getChildAt( 2 ) == null ) { TextView tv = (TextView)inflater.inflate(R.layout.text, null ); lLayout.addView(tv); } } }); } } |
3.) Compile and build the project.
Output
No comments:
Post a Comment