GUI


Layout

The layout of each activity is an XML file that manages where the controls (GUI elements) are placed in the activity. Use the folder app > res > layout to store the layout of each activity. You can optionally nest layout to produce a very specific control distribution. Some property examples of the layouts are:
  • android:gravity="center_horizontal"
  • android:gravity="center_vertical"
  • android:gravity="top"
  • android:gravity="bottom"
  • android:gravity="left"
  • android:gravity="right"
  • android:gravity="center"
  • android:gravity="fill_vertical"
  • android:gravity="fill_horizontal"
  • android:gravity="clip_vertical"
  • android:gravity="clip_horizontal"
  • android:orientation="horizontal" //A row of controls
  • android:orientation="vertical" //A column of controls
  • android:layout_width="match_parent"
  • android:layout_height="wrap_content"
  • android:background=="#ffffff"

El layout de cada actividad es un archivo de XML que administra dónde los controles (elementos GUI) son ubicados en la activity. Use la carpeta app > res > layout

Tip
Android team recommends using the ConstrainLayout.
El equipo de Android recomienda usar el ConstrainLayout.

Problem 1
Create an Android application called DropDown to test a Spinner. DO NOT check AppCompatActivity when creating the project. We will use an empty activity with a Spinner and a TextView.
Cree una aplicación para Android llamada DropDown to test a Spinner. NO marque la opción de AppCompatActivity al crear el proyecto. Nosotros usaremos una "empty activity" con un Spinner y una TextView.

DropDownRun

DropDownCreate

DropDownEmptyActivity

DropDownConfigureActivity

DropDrownInsert

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

     <Spinner
          android:id="@+id/spinMonth"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginTop="8dp"
          android:background="@android:drawable/btn_dropdown"
          android:spinnerMode="dropdown"
          app:layout_constraintTop_toTopOf="parent" />

     <TextView
          android:id="@+id/tbxOutput"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginBottom="8dp"
          android:text="Select a month!"
           android:textSize="40sp"
           app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java
package com.selo.dropdown;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity implements android.widget.AdapterView.OnItemSelectedListener
{
     private TextView tbxOutput = null;
     private Spinner spinnerMonth = null;
     private static final String[] months = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          //___________________________________________________ 1. Find GUI controls
          tbxOutput = (TextView)findViewById(R.id.tbxOutput);
          spinnerMonth= (Spinner)findViewById(R.id.spinMonth);
          //___________________________________________________ 2. Spinner setup
          ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
          android.R.layout.simple_spinner_item, months);

          adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          spinnerMonth.setAdapter(adapter);
          spinnerMonth.setOnItemSelectedListener(this);
          tbxOutput.setText("No selection");
     }

     @Override
     public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
     {
          switch (position)
          {
          case 0:
               tbxOutput.setText("Happy new year");
               break;
          case 1:
               tbxOutput.setText("Valentine's day");
               break;
          case 2:
               tbxOutput.setText("Spring is here");
               break;
          case 11:
               tbxOutput.setText("Christmas is here");
               break;
          default:
               tbxOutput.setText("Enjoy!");
          }
     }

     @Override
     public void onNothingSelected(AdapterView<?> arg0)
     {
     }
}


Problem 2
Create an Android application called MyDays to test a set of radio buttons. DO NOT check AppCompatActivity when creating the project. We will use an empty activity for this problem.
Cree una aplicación para Android llamada MyDays to test un conjunto de radio buttons. NO marque la opción de AppCompatActivity al crear el proyecto. Nosotros usaremos una "empty activity" para este problema.

MyDaysRun

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity">

     <RadioGroup
     android:id="@+id/radioGroupDay"
     android:gravity="left"
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:orientation="vertical">

     <RadioButton
     android:id="@+id/radioMonday"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Monday"
     android:onClick="radioMonday_Click"/>

     <RadioButton
     android:id="@+id/radioTuesday"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Tuesday"
     android:onClick="radioTuesday_Click"/>

     <RadioButton
     android:id="@+id/radioWednesday"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Wednesday"
     android:onClick="radioWednesday_Click"/>

     <RadioButton
     android:id="@+id/radioThursday"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Thursday"
     android:onClick="radioThursday_Click"/>

     <RadioButton
     android:id="@+id/radioFriday"
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="Friday"
     android:onClick="radioFriday_Click"/>
     </RadioGroup>

     <TextView
     android:id="@+id/tbxOutput"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginBottom="8dp"
     android:text="Select a day"
     android:textSize="40sp"
     app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java
package com.selo.mydays;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.TextView;
import android.view.View;

public class MainActivity extends Activity
{
     RadioButton radioMonday = null;
     TextView tbxOutput = null;
     @Override
          protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          //____________________________________________________ Select Monday
          radioMonday = (RadioButton)findViewById(R.id.radioMonday);
          radioMonday.setChecked(true);
          //____________________________________________________ tbxOutput
          tbxOutput = (TextView)findViewById(R.id.tbxOutput);
     }

     public void radioMonday_Click(View view)
     {
          tbxOutput.setText("First day of work");
     }

     public void radioTuesday_Click(View view)
     {
          tbxOutput.setText("Pizza");
     }

     public void radioWednesday_Click(View view)
     {
          tbxOutput.setText("Middle");
     }

     public void radioThursday_Click(View view)
     {
          tbxOutput.setText("Almost");
     }

     public void radioFriday_Click(View view)
      {
          tbxOutput.setText("Happy");
     }

}


Problem 3
Create an Android application called OurDinner to test the checkboxes. You can use in the XML file CheckBox or ToggleButton.
Cree una aplicación para Android llamada OurDinner para probar las checkboxes. Uste puede usar en el archivo de XML CheckBox o ToggleButton.

OurDinnerRun

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">
     tools:context=".MainActivity">

     <CheckBox
     android:id="@+id/ckWater"
     android:text="Water"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="ckWater_Click"/>

     <CheckBox
     android:id="@+id/ckPizza"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="ckPizza_Click"
     android:text="Pizza"
     app:layout_constraintTop_toBottomOf="@+id/ckWater" />

     <CheckBox
     android:id="@+id/ckFrechFries"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="ckFrechFries_Click"
     android:text="Frech Fries"
     app:layout_constraintTop_toBottomOf="@+id/ckPizza" />

     <CheckBox
     android:id="@+id/ckIceCream"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="ckIceCream_Click"
     android:text="Ice Cream"
     app:layout_constraintTop_toBottomOf="@+id/ckFrechFries" />

     <TextView
     android:id="@+id/tbxOutput"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_marginBottom="8dp"
     android:text="Select your dinner"
     android:textSize="40sp"
     app:layout_constraintBottom_toBottomOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.java
package com.selo.ourdinner;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.ToggleButton;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity
{
     CheckBox ckWater = null;
     CheckBox ckPizza = null;
     CheckBox ckFrechFries = null;
     CheckBox ckIceCream = null;
     TextView tbxOutput = null;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          ckWater = (CheckBox)findViewById(R.id.ckWater);
          ckPizza = (CheckBox)findViewById(R.id.ckPizza);
          ckFrechFries = (CheckBox)findViewById(R.id.ckFrechFries);
          ckIceCream = (CheckBox)findViewById(R.id.ckIceCream);
          tbxOutput = (TextView)findViewById(R.id.tbxOutput);
     }

     void Update()
     {
          String text = new String();
          if (ckWater.isChecked() == true) text += "Water ";
          if (ckPizza.isChecked() == true) text += "Pizza ";
          if (ckFrechFries.isChecked() == true) text += "Fries ";
          if (ckIceCream.isChecked() == true) text += "Ice Cream ";
          tbxOutput.setText(text);
     }

     public void ckWater_Click(View view)
     {
          Update();
     }

     public void ckPizza_Click(View view)
     {
          Update();
     }

     public void ckFrechFries_Click(View view)
     {
          Update();
     }

     public void ckIceCream_Click(View view)
     {
          Update();
     }

}


android.content.Intent

An "Android" intent is used to open an Activity from another Activity. To create a new "intent", you need two activities: the current Activity and the next Activity. To open the new Activity, you can call: startActivitity o startActivityForResult. startActivityForResult is called when you need to send back data from the new Activity to the original Activity, in this case, you need to implement the onActivityResult function.
Una "intent" de Android es usado para abrir una Activity desde otra Activity. Para crear un nuevo "intent", usted necesita dos actividades: la Activity corriente y la próxima Activity. Para abrir la Activity nueva, usted puede llamar: startActivity o startActivityForResult. startActivityForResult es llamado cuando se necesita enviar datos de regreso desde la nueva actividad a la actividad original, en este caso, usted tiene que implementar la función onActivityResult.

intent.putExtra

This function is used to send data from one Activity to another one.
Esta función es usada para enviar datos desde una Activity a otra.

Problem 4
Create an Android application called Question with an "Empty Activity". This problem illustrates how to open two activities. This problem also illustrates how to move data from one Activity to another Activity.
Cree una aplicación para Android llamada Question con una "Empty Activity". Este problema ilustra cómo abrir dos actividades. Este problema también ilustra cómo mover datos desde una Activity a otra Activity.

Step A
Edit the files of the "Main Activity" as shown.
Edite los archivos de la "Main Activity" como se muestra.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity">

     <TextView
     android:id="@+id/tbxFriendName"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Peter"
     android:textSize="40dp"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

     <Button
     android:id="@+id/btEditName"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Edit Friend Name"
     android:padding="20pt"
     android:onClick="btEdit_Click"
     app:layout_constraintTop_toBottomOf="@+id/tbxFriendName" />

     </androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java

package com.selo.question;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
import android.content.Intent;

public class MainActivity extends Activity
{
     private TextView tbxFriendName = null;
     private Button btEditName = null;
     static final int ASK_QUESTION_REQUEST = 1;

     @Override
          protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          //___________________________________________________ 1. Find GUI controls
          tbxFriendName = (TextView)findViewById(R.id.tbxFriendName);
          btEditName= (Button)findViewById(R.id.btEditName);
     }

     public void btEdit_Click(View view)
     {
          //___________________________________________________ 2. Send current friend name
          Intent intent = new Intent(this, EditActivity.class);
          if (tbxFriendName.getText().length() > 0)
          {
               intent.putExtra("friendName", tbxFriendName.getText());
          }
          //___________________________________________________ 3. Open EditActivity
          startActivityForResult(intent, ASK_QUESTION_REQUEST);
          //startActivity(intent);
     }

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent intent)
     {
          if (resultCode == RESULT_OK && requestCode == ASK_QUESTION_REQUEST)
          {
               //___________________________________________________ 3. Receive the new name
               Bundle extras = intent.getExtras();
               if (extras != null)
               {
                    String name = extras.getString("friendName");
                    //_________________________________________________4. Display the new name
                    if (name != null)
                    {
                         tbxFriendName.setText(name);
                    }
               }
          }
     }
}


Step B
From the left panel select app > res > layout , then right click to open the context menu to create an Activity: New > Activity > Empty Activity . Set the name of this Activity to "EditActivity".
Desde el panel de la izquierda selecciona app > res > layout , entonces haz clic con el botón derecho del ratón para abrir el menú de contexto para crear una Activity: New > Activity > Empty Activity . Fije el nombre de esta Activity a "EditActivity".

EditActivity

QuestionRun1

QuestionRun2

QuestionRun3

QuestionRun4

activity_edit.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".EditActivity">

     <EditText
     android:id="@+id/tbxName"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:hint="Type name here"
     android:textSize="40dp"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

     <Button
     android:id="@+id/btOK"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="OK"
     android:padding="20pt"
     android:onClick="btOK_Click"
     app:layout_constraintTop_toBottomOf="@+id/tbxName" />

     <Button
     android:id="@+id/btCancel"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Cancel"
     android:padding="20pt"
     android:onClick="btCancel_Click"
     app:layout_constraintTop_toBottomOf="@+id/btOK" />

</androidx.constraintlayout.widget.ConstraintLayout>


EditActivity.java
package com.selo.question;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;

public class EditActivity extends Activity
{
     private EditText tbxName = null;
     private Button btOK = null;

     @Override
          protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_edit);
          //___________________________________________________ 1. Find GUI controls
          tbxName = (EditText)findViewById(R.id.tbxName);
          btOK= (Button)findViewById(R.id.btOK);
          //___________________________________________________ 2. Pre-fill the textbox
          Bundle extras = getIntent().getExtras();
          if (extras != null)
          {
               String name = extras.getString("friendName");
               tbxName.setText(name);
          }
     }

     public void btOK_Click(View view)
     {
          //___________________________________________________ 3. Send back the new friend name
          if (tbxName.getText().length() > 0)
          {
               Intent intent = new Intent(this, MainActivity.class);
               intent.putExtra("friendName", tbxName.getText().toString());
               setResult(RESULT_OK, intent);
               finish();
          }
     }

     public void btCancel_Click(View view)
     {
          finish();
     }
}


Problem 5
Create an Android application called Fruit with an "Empty Activity". This problem illustrates how to use a ListView. This problem also illustrates how to move data from one Activity to another Activity. The figure below shows the final view of all files required for this problem, the following steps will explain how to create each file. This problem is organized as follows:
  1. The main Activity with a ListView
  2. The FruitInfo class so store an item in the ListView
  3. An ArrayAdapter called FruitAdapter to store the items in the ListView
  4. An XML Layout file (fruit_info.xml) to indicate how to display the items in the ListView
  5. A second Activity that opens when an item in the ListView control is selected

Cree una aplicación para Android llamada Fruit con una "Empty Activity". Este problema ilustra cómo usar un ListView. Este problema también ilustra cómo mover datos desde una Activity a otra Activity. La figura de abajo muestra la vista final de todos los archivos requeridos para este problema, los pasos siguientes explicarán como crear cada archivo. Este problema está organizado como sigue:
  1. La principal Activity con un ListView
  2. La clase FruitInfo para almacenar un artículo del ListView
  3. Un ArrayAdapter llamado FruitAdapter para almacenar los datos del ListView
  4. Un archivo de XML Layout (fruit_info.xml) para indicar como mostrar los artículos en el ListView
  5. Una Activity adicional que se abre cuando un artículo en el ListView se selecciona

FruitRun1

FruitRun2

FruitLeftPanel

Step A
Add a Java class called FruitInfo, from the left panel open app > java > com.selo.fruit , then right click to open the context menu New > class.
Agregue una clase de Java llamada FruitInfo, desde el panel de la izquierda abra app > java > com.selo.fruit , entonces haga clic con el botón derecho del ratón para abrir el menú de contexto New > class.

FruitInfo.java

package com.selo.fruit;

public class FruitInfo
{
     public String name;
     public String color;

     public FruitInfo(String name, String color)
     {
          this.name = name;
          this.color = color;
     }
}


Step B
Add a XML layout file called fruit_info.xml, from the left panel open app > res > layout , then right click to open the context menu New > Layout resource file.
Agregue un archivo de XML layout llamado fruit_info.xml, en el panel de la izquierda abra app > res > layout , entonces haga clic con el botón derecho del ratón New > Layout resource file.

fruit_info.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

     <TextView
     android:id="@+id/tbxName"
     android:layout_width="100dp"
     android:layout_height="wrap_content"
     android:text="Name" />

     <TextView
     android:id="@+id/tbxColor"
     android:layout_width="100dp"
     android:layout_height="wrap_content"
     android:text="Color" />

     </LinearLayout>


Step C
Add a Java class called FruitAdapter, from the left panel open app > java > com.selo.fruit, then right click to open the context menu New > class.
Agregue una clase de Java llamada FruitAdapter, desde el panel de la izquierda abra app > java > com.selo.fruit , entonces haga clic con el botón derecho del ratón para abrir el menú de contexto New > class.

FruitAdapter.java
package com.selo.fruit;

import android.widget.ArrayAdapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.LayoutInflater;
import java.util.ArrayList;

public class FruitAdapter extends ArrayAdapter<FruitInfo>
{
     public FruitAdapter(Context context, ArrayList<FruitInfo> fruitInfo)
     {
          super(context, 0, fruitInfo);
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent)
     {
          // Get the data item for this position
          FruitInfo fruitInfo = getItem(position);
          // Check if an existing view is being reused, otherwise inflate the view
          if (convertView == null)
          {
               convertView = LayoutInflater.from(getContext()).inflate(R.layout.fruit_info, parent, false);
          }
          // Lookup view for data population
          TextView tbxName = (TextView)convertView.findViewById(R.id.tbxName);
          TextView tbxColor = (TextView)convertView.findViewById(R.id.tbxColor);
          // Populate the data into the template view using the data object
          tbxName.setText(fruitInfo.name);
          tbxColor.setText(fruitInfo.color);
          // Return the completed view to render on screen
          return convertView;
     }
}


Step D
From the left panel select app > res > layout , then right click to open the context menu to create an Activity: New > Activity > Empty Activity . Set the name of this Activity to "FruitActivity".
Desde el panel de la izquierda selecciona app > res > layout , entonces haz clic con el botón derecho del ratón para abrir el menú de contexto para crear una Activity: New > Activity > Empty Activity . Fije el nombre de esta Activity a "FruitActivity".

FruitActivity

activity_fruit.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".FruitActivity">

     <EditText
     android:id="@+id/tbxName"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:hint="Type name here"
     android:textSize="40dp"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     app:layout_constraintTop_toTopOf="parent" />

     <Button
     android:id="@+id/btOK"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="OK"
     android:padding="20pt"
     android:onClick="btOK_Click"
     app:layout_constraintTop_toBottomOf="@+id/tbxName" />

</androidx.constraintlayout.widget.ConstraintLayout>


Step E
Edit the files of the "Main Activity" as shown.
Edite los archivos de la "Main Activity" como se muestra.

activity_mail.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ListView
android:id="@+id/lvFruit"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.java
package com.selo.fruit;

import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ListView;
import android.view.View;
import android.content.Intent;
import java.util.ArrayList;


public class MainActivity extends Activity implements AdapterView.OnItemClickListener
{
     private ListView lvFruit = null;
     private FruitAdapter fruitAdapter = null;
     static final int REQUEST_RESPONSE = 1;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          //_______________________________________________________ 1. Create the Fruit Adapter
          ArrayList<FruitInfo> fruit = new ArrayList<FruitInfo>();
          fruitAdapter = new FruitAdapter(this, fruit);
          //_______________________________________________________ 2. Fill the Fruit Adapter
          fruitAdapter.add(new FruitInfo("Apple", "red"));
          fruitAdapter.add(new FruitInfo("Orange", "yellow"));
          fruitAdapter.add(new FruitInfo("Grapes", "purple"));
          fruitAdapter.add(new FruitInfo("Strawberry", "red"));
          fruitAdapter.add(new FruitInfo("Banana", "yellow"));
          fruitAdapter.add(new FruitInfo("Lime", "green"));
          fruitAdapter.add(new FruitInfo("Pineapple", "brown"));
          //________________________________________________________ 1. List View setup
          lvFruit = (ListView)findViewById(R.id.lvFruit);
          lvFruit.setAdapter(fruitAdapter);
          lvFruit.setOnItemClickListener(this);
     }

     @Override
     public void onItemClick(AdapterView<?> adapterView, View view, int position, long id)
     {
          //___________________________________________________________ 4. Send the fruit name to FruitActivity
          FruitInfo fruitInfo = (FruitInfo)fruitAdapter.getItem(position);
          if (fruitInfo != null)
          {
               Intent intent = new Intent(this, FruitActivity.class);
               intent.putExtra("fruit_name", fruitInfo.name);
               //______________________________________________________ 5. Open FruitActivity
               startActivityForResult(intent, REQUEST_RESPONSE);
          }
     }
}


© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home