- Программное добавление и удаление виджета
- Добавляем виджет
- Удаляем виджет
- activity_main.xml
- layer1.xml
- layer2.xml
- Tutorialwing
- Output
- Getting Started
- 1. Creating New Project
- 2. Modify values folder
- 3. Modify Layout Folder
- 4. Create Android ImageView Programmatically / Dynamically
- AndroidManifest.xml file
- Tutorialwing
- Output
- Getting Started
- 1. Creating New Project
- 2. Modify values folder
- 3. Create Views that replaces ViewStub
- 4. Modify Layout Folder
- 5. Create Android ViewStub Programmatically / Dynamically
- AndroidManifest.xml file
- Tutorialwing
- Output
- Video Output
- 1. Creating New Project
- 2. Modify Values Folder
- 3. Modify Layout Folder
- 4.Create Android TextView Programmatically / Dynamically
- AndroidManifest.xml file
Программное добавление и удаление виджета
Обычно мы размещаем виджеты через XML. Но можно это делать и программно. Такой подход используется при динамическом размещении, когда неизвестно, сколько элементов должно быть на экране.
Добавляем виджет
Допустим у нас есть простейшая разметка.
Пустая компоновка LinearLayout с идентификатором mainlayout не содержит вложенных виджетов. Через метод addView(view) класса LinearLayout мы можем добавить нужный нам элемент.
Удаляем виджет
Существует и обратный метод для удаления вида — removeView(), а также метод removeAllViews(), удаляющий все дочерние элементы родителя. Рассмотрим следующий пример. Создадим разметку, где компонент LinearLayout с идентификатором master будет родителем для будущих элементов, которые мы будем добавлять или удалять:
activity_main.xml
Создадим пару дополнительных макетов, которые будет дочерними элементами для FrameLayout. Мы будем управлять ими программно.
layer1.xml
layer2.xml
Напишем код, который будет добавлять или удалять компоновки через флажки.
Обратите внимание, что добавление идёт в том порядке, как мы отмечаем флажки. Если мы отметим флажком второй CheckBox, то сначала на экране появится блок с компоновкой layer2.xml, а уже ниже компоновка layer1.xml. На скриншоте представлен этот вариант.
Получить доступ к дочерним элементам можно через методы getChildCount() и getChildAt().
Источник
Tutorialwing
Hello Readers! In this post, we are going to learn how to create and use android imageView programmatically in any android application. We will also learn to add imageView in linearLayout programmatically in any application.
Output
Tutorialwing Android Dynamic ImageView Output
Tutorialwing Android Dynamic ImageView Output
Getting Started
At first, we will create an android application. Then, we will use imageView widget in the application.
1. Creating New Project
Follow the steps below to create a new project. Please ignore the steps if you have already created a new project.
Step | Description |
---|---|
1. | Open Android Studio. |
2. | Go to File => New => New Project. Write application name as DynamicImageView. Then, click next button. |
3. | Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button |
4. | Then, select Empty Activity => click next => click finish. |
5. | If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail. |
Now, we will modify xml and java file to use android imageView programmatically.
2. Modify values folder
No values folders have been modified. So, we are not going to mention them here.
3. Modify Layout Folder
Open res/layout/activity_main.xml file. Then, add below code into it.
In activity_main.xml file, we have defined linearLayout and button widget. Now, we will create imageView programmatically in android application. Then, we will add this imageView in linearLayout.
4. Create Android ImageView Programmatically / Dynamically
Open app/src/main/java/com.tutorialwing.dynamicimageview/MainActivity.java file and add below code into it.
In MainActivity.java file, we have created imageView programmatically. Then, we have set it’s layout params and image resource. After that, we have set click listener of button to change image in imageView. At last, we have added this widget in linearLayout, with id rootContainer.
Since AndroidManifest.xml file is very important in any android project. We are also going to see the content inside this file.
AndroidManifest.xml file
Code inside src/main/AndroidManifest.xml file would look like below –
When we run the application, we will get output as shown above.
That’s the end of tutorial on Creating Android ImageView Programmatically.
Источник
Tutorialwing
Hello Readers! In this post, we are going to learn how to create and use android viewStub programmatically in any android application. We will also learn to add viewStub in linearLayout programmatically in any application.
Output
Tutorialwing Android Dynamic ViewStub Output
Tutorialwing Android Dynamic ViewStub Output
Getting Started
At first, we will create an android application. Then, we will use viewStub widget in the application.
1. Creating New Project
Follow the steps below to create a new project. Please ignore the steps if you have already created a new project.
Step | Description |
---|---|
1. | Open Android Studio. |
2. | Go to File => New => New Project. Write application name as DynamicViewStub. Then, click next button. |
3. | Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button |
4. | Then, select Empty Activity => click next => click finish. |
5. | If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail. |
Now, we will modify xml and java file to use android viewStub programmatically.
2. Modify values folder
Open res/values/strings.xml file and add below code into it.
3. Create Views that replaces ViewStub
Whenever we call viewStub.inflate() or viewStub.setVisibility(true), viewStub replaces itself with another views. So, we will define that view now. Create an xml file, sub_item.xml file, in res/layout folder. Add below code into this file.
Here, we have defined the view that replaces viewStub when inflate() method is called.
4. Modify Layout Folder
Open res/layout/activity_main.xml file. Then, add below code into it.
In activity_main.xml file, we have defined linearLayout, with id rootContainer, that will act as container for the viewStub created dynamically in the application. We have also defined a button that are used to toggle the display of view inflated by viewStub.
5. Create Android ViewStub Programmatically / Dynamically
Open app/src/main/java/com.tutorialwing.dynamicviewstub/MainActivity.java file and add below code into it.
In MainActivity.java file, we have created viewStub programmatically in the application. Then, we have set layout params, margins etc. in it. setLayoutResource() method is called to specifies layout that will replace viewStub when inflate() or setVisibility(true) method is called. We have also set listener to button that toggle the visibility of inflated view by viewStub.
Since AndroidManifest.xml file is very important in any android project. We are also going to see the content inside this file.
AndroidManifest.xml file
Code inside src/main/AndroidManifest.xml file would look like below –
When we run the application, we will get output as shown above.
That’s the end of tutorial on Creating Android ViewStub Programmatically.
Источник
Tutorialwing
Hello Readers! In this post, you will learn how to create TextView programmatically in android. You will go through different steps that explains to create Textview dynamically and adding it in java file.
Output
Tutorialwing Dynamic TextView Tutorial Output
Tutorialwing Dynamic TextView Tutorial Output
Video Output
First step is to create New Project. Follow the steps below to create new project. Please ignore the steps if you have already created project.
1. Creating New Project
Step | Description |
---|---|
1. | Open Android Studio. |
2. | Go to File => New => New Project. Write application name as DynamicTextView. Then, click next button. |
3. | Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button |
4. | Then, select Empty Activity => click next => click finish. |
5. | If you have followed above process correctly, you will get a newly created project successfully. However, you can also visit post to create a new project to know steps in detail. |
Now, we will modify the xml and java files to create TextView programmatically and add it in xml file. Please follow the steps below.
2. Modify Values Folder
Open res/values/strings.xml file and add below code into it.
Other values folders have not been changed. So, we are not going to mention it here.
3. Modify Layout Folder
Open res/layout/activity_main.xml file. Add below code into it.
Note that LinearLayout has id rootLayout. In Java file, we will create TextView dynamically and add it into this LinearLayout having id rootLayout.
4.Create Android TextView Programmatically / Dynamically
Open src/main/java/com.tutorialwing.dynamictextview/MainActivity.java file. Then, add below code into it. You may also visit post to use Textview widget in xml file in android
Note that we are creating TextView Dynamically. Then, We have added it’s layoutParams, gravity and other attributes dynamically. Finally, added this TextView in LinearLayout having id rootLayout.
AndroidManifest.xml file
Since AndroidManifest file is very important for project. We are also going to mention it here. Code inside main/AndroidManifest.xml file is as below.
Finally, when you run the application, you will get output as shown above.
Источник