Продолжаем изучать обмен данными между экранами android приложения. В этом уроке создаем android приложение, которое будет вызывать два разных Activity и получать от них данные. Как мы помним, результат приходит в метод onActivityResult. И requestCode используется, чтобы отличать друг от друга пришедшие результаты. А resultCode – позволяет определить, успешно прошел вызов или нет.
Исходный код классов из урока — под видео:
[pastacode lang=»css» message=»activity_main.xml» highlight=»» provider=»manual»]
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <TextView android:id="@+id/tvText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:text="Hello World" android:textSize="20sp"> </TextView> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:orientation="horizontal"> <Button android:id="@+id/btnColor" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:layout_weight="1" android:text="Color"> </Button> <Button android:id="@+id/btnAlign" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_weight="1" android:text="Alignment"> </Button> </LinearLayout> </LinearLayout> |
[/pastacode]
[pastacode lang=»java» message=»MainActivity.java» highlight=»» provider=»manual»]
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
package info.fandroid.activityresult; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ final int REQUEST_CODE_COLOR = 1; final int REQUEST_CODE_ALIGN = 2; TextView tvText; Button btnColor; Button btnAlign; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvText = (TextView)findViewById(R.id.tvText); btnColor = (Button)findViewById(R.id.btnColor); btnAlign = (Button)findViewById(R.id.btnAlign); btnAlign.setOnClickListener(this); btnColor.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent; switch (v.getId()){ case R.id.btnColor: intent = new Intent(this, ColorActivity.class); startActivityForResult(intent, REQUEST_CODE_COLOR); break; case R.id.btnAlign: intent = new Intent(this, AlignActivity.class); startActivityForResult(intent, REQUEST_CODE_ALIGN); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.d("myLogs", "requestCode = " + requestCode + ", resultCode = " + resultCode); if (resultCode == RESULT_OK){ switch (requestCode){ case REQUEST_CODE_COLOR: int color = data.getIntExtra("color", Color.WHITE); tvText.setTextColor(color); break; case REQUEST_CODE_ALIGN: int align = data.getIntExtra("alignment", Gravity.LEFT); tvText.setGravity(align); break; } } else { Toast.makeText(MainActivity.this, "Wrong result", Toast.LENGTH_SHORT).show(); } } } |
[/pastacode]
[pastacode lang=»css» message=»activity_color.xml» highlight=»» provider=»manual»]
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 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="info.fandroid.activityresult.ColorActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="red" android:id="@+id/btnRed" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="green" android:id="@+id/btnGreen" android:layout_alignTop="@+id/btnRed" android:layout_centerHorizontal="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="blue" android:id="@+id/btnBlue" android:layout_alignTop="@+id/btnGreen" android:layout_alignParentEnd="true" /> </RelativeLayout> |
[/pastacode]
[pastacode lang=»java» message=»ColorActivity.java» highlight=»» provider=»manual»]
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 42 43 44 45 46 47 48 49 |
package info.fandroid.activityresult; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class ColorActivity extends AppCompatActivity implements View.OnClickListener{ Button btnRed; Button btnGreen; Button btnBlue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_color); btnRed = (Button)findViewById(R.id.btnRed); btnGreen = (Button)findViewById(R.id.btnGreen); btnBlue = (Button)findViewById(R.id.btnBlue); btnRed.setOnClickListener(this); btnGreen.setOnClickListener(this); btnBlue.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(); switch (v.getId()){ case R.id.btnRed: intent.putExtra("color", Color.RED); break; case R.id.btnGreen: intent.putExtra("color", Color.GREEN); break; case R.id.btnBlue: intent.putExtra("color", Color.BLUE); break; } setResult(RESULT_OK, intent); finish(); } } |
[/pastacode]
[pastacode lang=»css» message=»activity_align.xml» highlight=»» provider=»manual»]
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="info.fandroid.activityresult.AlignActivity"> <Button android:id="@+id/btnLeft" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:text="Left" /> <Button android:id="@+id/btnCenter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/btnLeft" android:layout_centerHorizontal="true" android:text="Center" /> <Button android:id="@+id/btnRight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/btnCenter" android:layout_alignParentEnd="true" android:text="Right" /> </RelativeLayout> |
[/pastacode]
[pastacode lang=»java» message=»AlignActivity.java» highlight=»» provider=»manual»]
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 42 43 44 45 46 47 48 49 |
package info.fandroid.activityresult; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.Button; public class AlignActivity extends AppCompatActivity implements View.OnClickListener{ Button btnLeft; Button btnCenter; Button btnRight; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_align); btnLeft = (Button)findViewById(R.id.btnLeft); btnCenter = (Button)findViewById(R.id.btnCenter); btnRight = (Button)findViewById(R.id.btnRight); btnLeft.setOnClickListener(this); btnCenter.setOnClickListener(this); btnRight.setOnClickListener(this); } @Override public void onClick(View v) { Intent intent = new Intent(); switch (v.getId()){ case R.id.btnLeft: intent.putExtra("alignment", Gravity.LEFT); break; case R.id.btnCenter: intent.putExtra("alignment", Gravity.CENTER); break; case R.id.btnRight: intent.putExtra("alignment", Gravity.RIGHT); break; } setResult(RESULT_OK, intent); finish(); } } |
[/pastacode]
Больше уроков:
Инструменты android разработчика: тут
Дизайн android приложений: тут
Уроки создания игр для android: тут
Основы программирования на JAVA: тут
<<Урок 29. Вызов второго Activity с возвращением данных | Уроки Android Studio
Урок 31. Вызываем браузер, звонилку, карты с помощью intent с атрибутом data — Uri >>