Lesson 17. Creating a View Component in a Work Application

Lesson 17. Creating a View Component in a Work Application


In this lesson we:

– Add components to the screen directly from the application

In the last lesson, we created components in the Activity.onCreate method, that is, when creating a program. In this lesson, we will create an already working application. We will create Button-s, because they are most clearly displayed. We will specify the text that will be displayed on the button and the alignment: left, center or right. Also, we can delete the created items.

Let’s create a project:

Project name: P0171_DynamicLayout2
Build Target: Android 2.3.3
Application name: DynamicLayout2
Package name: ru.startandroid.develop.dynamiclayout2
Create Activity: MainActivity

Let’s create a screen to help us create View components. open main.xml and we write the following there:



    
        
        
        
        
        
        
    
    
        
        
        
        
    
    
    

Consider the screen in detail.

rgGravity is a RadioGroup, with three RadioButton (rbLeft, rbCenter, rbRight). We use this component to select the alignment of the component being created
etName – text box, here we will specify the text that will be displayed on the created component
btnCreate is the button that starts the creation process.
btnClear – a button that washes everything they created
llMain is a vertical LinearLayout in which components will be created

Screen ready, let’s code implementation. open MainActivity.java. Let’s start by describing and finding all the components we need. By the way, we have a couple of buttons that we will use, so they need a handler. As handler assignable Activity (That is, you need to add: implements OnClickListener) and let’s create an empty while processing method onClick:

public class MainActivity extends Activity implements OnClickListener{

  LinearLayout llMain;
  RadioGroup rgGravity;
  EditText etName;
  Button btnCreate;
  Button btnClear;

int wrapContent = LinearLayout.LayoutParams.WRAP_CONTENT;

  
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    llMain = (LinearLayout) findViewById(R.id.llMain);
    rgGravity = (RadioGroup) findViewById(R.id.rgGravity);
    etName = (EditText) findViewById(R.id.etName);

    btnCreate = (Button) findViewById(R.id.btnCreate);
    btnCreate.setOnClickListener(this);

    btnClear = (Button) findViewById(R.id.btnClear);
    btnClear.setOnClickListener(this);
  }


  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    
  }
}

I also created a variable wrapContent and will store LinearLayout.LayoutParams.WRAP_CONTENT in it. I only do this to reduce the cumbersome code.

Now let’s describe the process of creating a Button component by completing the onClick method:

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnCreate:
      // Создание LayoutParams c шириной и высотой по содержимому
      LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
          wrapContent, wrapContent);
      // переменная для хранения значения выравнивания
      // по умолчанию пусть будет LEFT
      int btnGravity = Gravity.LEFT;
      // определяем, какой RadioButton "чекнут" и 
      // соответственно заполняем btnGravity 
      switch (rgGravity.getCheckedRadioButtonId()) {
      case R.id.rbLeft:
        btnGravity = Gravity.LEFT;
        break;
      case R.id.rbCenter:
        btnGravity = Gravity.CENTER_HORIZONTAL;
        break;
      case R.id.rbRight:
        btnGravity = Gravity.RIGHT;
        break;
      }
      // переносим полученное значение выравнивания в LayoutParams
      lParams.gravity = btnGravity;

      // создаем Button, пишем текст и добавляем в LinearLayout
      Button btnNew = new Button(this);
      btnNew.setText(etName.getText().toString());
      llMain.addView(btnNew, lParams);

      break;
    }
  }

Let’s consider the written. First, we check that the button has been pressed btnCreate – that is, the create button. then create LayoutParams with height and width on hold. Here I used the variable I wrote about above – wrapContent. Otherwise it would turn out quite cumbersome.

Next we create a variable btnGravity, By which we write the value of the LEFT alignment by default. To determine which RadioButton is currently selected, we use the method getCheckedRadioButtonId – he returns RadioButton’s “check” ID to RadioGroup. We compare it with our three IDs and enter the corresponding value into the btnGravity variable. We reset this value in gravity in LayoutParams.

Next, create a button and assign it a text from etName. Note that it is not enough to write getText because it will not provide text. The toString method still needs to be called. And finally add the created Button to our LinearLayout.

Let’s save everything and launch the application. Add a few buttons.

Buttons should appear with the specified alignment and text.

As you type, the keyboard appears below and closes the overview. To make it disappear, you must press the Back button on the emulator or ESC on a regular keyboard. If the keyboard appears Japanese with hieroglyphs, open the shortcut menu for the input field (long left-click), press Input method and select Android Keyboard from the list.

Button left unrealized ClearWhich is intended to delete everything created. To do this, we need to supplement the method onClick, We add in switch (v.getId()) another case:

    case R.id.btnClear:
      llMain.removeAllViews();
      Toast.makeText(this, "Удалено", Toast.LENGTH_SHORT).show();
      break;

method removeAllViews removes all child View components from our LinearLayout. Using Toast is displayed message about success. Let’s save, run and check. Add some buttons, press a button Clear and observe the result:

As a result, we have a very dynamic application that can change itself.

The forum asks: how to then access these created components. Here are a couple of simple options.

1) When creating, you can assign the ID components yourself. This is done by the setId method. And then just call that findViewById with that ID.

2) You can store the created components in your array or list. Or you can use the getChildAt method. Calling this method for llMain will allow it to get its child components by the index. GetChildCount method will allow getting the number of child elements.

Full lesson code:

public class MainActivity extends Activity implements OnClickListener {

  LinearLayout llMain;
  RadioGroup rgGravity;
  EditText etName;
  Button btnCreate;
  Button btnClear;

  int wrapContent = LinearLayout.LayoutParams.WRAP_CONTENT;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    llMain = (LinearLayout) findViewById(R.id.llMain);
    rgGravity = (RadioGroup) findViewById(R.id.rgGravity);
    etName = (EditText) findViewById(R.id.etName);

    btnCreate = (Button) findViewById(R.id.btnCreate);
    btnCreate.setOnClickListener(this);

    btnClear = (Button) findViewById(R.id.btnClear);
    btnClear.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnCreate:
      // Создание LayoutParams c шириной и высотой по содержимому
      LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(
          wrapContent, wrapContent);
      // переменная для хранения значения выравнивания
      // по умолчанию пусть будет LEFT
      int btnGravity = Gravity.LEFT;
      // определяем, какой RadioButton "чекнут" и
      // соответственно заполняем btnGravity
      switch (rgGravity.getCheckedRadioButtonId()) {
      case R.id.rbLeft:
        btnGravity = Gravity.LEFT;
        break;
      case R.id.rbCenter:
        btnGravity = Gravity.CENTER_HORIZONTAL;
        break;
      case R.id.rbRight:
        btnGravity = Gravity.RIGHT;
        break;
      }
      // переносим полученное значение выравнивания в LayoutParams
      lParams.gravity = btnGravity;

      // создаем Button, пишем текст и добавляем в LinearLayout
      Button btnNew = new Button(this);
      btnNew.setText(etName.getText().toString());
      llMain.addView(btnNew, lParams);

      break;

    case R.id.btnClear:
      llMain.removeAllViews();
      Toast.makeText(this, "Удалено", Toast.LENGTH_SHORT).show();
      break;

    }
  }

}

In the next lesson:

– change layout parameters for existing screen components




Discuss in the forum [142 replies]

Leave a Comment