Android | Создание приложения с несколькими экранами
В этой статье показано, как создать приложение для Android для перехода от одного занятия к другому.
Ниже приведены инструкции по созданию простого Android-приложения для перехода от одного занятия к другому.
ШАГ-1: Создайте новый проект, и экран вашего проекта будет выглядеть, как показано ниже.
ШАГ-2: У вас будет xml-файл и java-файл активности, путь к обоим файлам указан ниже.
ШАГ-3: Откройте XML-файл и добавьте кнопку, потому что после нажатия этой кнопки мы перейдем ко второму действию, как показано ниже. Добавьте TextView для сообщения. Назначьте идентификатор кнопке и TextView.
ШАГ 4: Теперь нам нужно создать другое действие (SecondActivity), чтобы переходить от одного действия к другому. Создайте второе действие и перейдите в проект Android> Файл> Новое> Действие> Пустое действие
ШАГ 5: Теперь откройте второй XML-файл, путь к нему такой же, как у первого XML-файла. Добавьте TexView для сообщений и добавьте 2 кнопки: одна предназначена для следующего действия, а вторая - для предыдущего действия. назначьте идентификатор для Textview и для обеих кнопок. Второе действие показано ниже:
ШАГ 6: Теперь нам нужно создать третье действие, такое же, как второе действие, и путь к этому файлу также такой же, как и к другому. («Теперь вы можете создать много таких действий»). Здесь мы добавляем TextView для сообщения и одну кнопку для перейти к предыдущему действию. Это будет показано ниже
ШАГ 7: Теперь откройте java-файл вашего первого действия. определите Button (next_button или может быть previous_button) и переменную TextView, используйте findViewById (), чтобы получить Button и TextView.
ШАГ 8: Нам нужно добавить прослушиватель кликов ко всем кнопкам (next_button или может быть previous_button).
ШАГ 9: Когда кнопка была нажата внутри метода onclicklistener, создайте намерение для запуска действия, называемого другим действием.
ШАГ 10: Повторите шаги 7, 8, 9 для каждого вида деятельности.
ШАГ 11: Теперь запустите приложение и нажмите кнопку, чтобы перейти ко второму действию.
В первом действии здесь только одна кнопка и TextView
Полный код OneActivity.java или activity_oneactivity.xml из Firstactivity приведен ниже.
activity_oneactivity.xml
<? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".Oneactivity" tools:layout_editor_absoluteY = "81dp" > < TextView android:id = "@+id/question1_id" android:layout_marginTop = "60dp" android:layout_marginLeft = "30dp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "" android:textStyle = "bold" android:textColor = "@android:color/background_dark" /> <!-- add button after click this we can goto another activity--> < Button android:id = "@+id/first_activity_button" android:layout_width = "150dp" android:layout_height = "40dp" android:layout_marginTop = "200dp" android:layout_marginLeft = "90dp" android:text = "Next" android:textStyle = "bold" android:textColor = "@android:color/background_dark" android:textSize = "15sp" /> </ RelativeLayout > |
OneActivity.java
// Each new activity has its own layout and Java files, package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Oneactivity extends AppCompatActivity { // define the global variable TextView question1; // Add button Move to Activity Button next_Activity_button; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_oneactivity); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button next_Activity_button = (Button)findViewById(R.id.first_activity_button); question1 = (TextView)findViewById(R.id.question1_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question1.setText( "Q 1 - How to pass the data between activities in Android?
" + "
" + "Ans- Intent" ); // Add_button add clicklistener next_Activity_button.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(Oneactivity. this , SecondActivity. class ); // start the activity connect to the specified class startActivity(intent); } }); } } |
Примечание. Здесь мы добавим кнопку «Далее», а также предыдущую кнопку и текстовое поле для сообщения.
Полный код SecondActivity.java или activity_second.xml второго действия приведен ниже.
activity_second.xml
<? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = "org.geeksforgeeks.navedmalik.multiplescreenapp.SecondActivity" > < TextView android:id = "@+id/question2_id" android:layout_marginTop = "60dp" android:layout_marginLeft = "30dp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "" android:textStyle = "bold" android:textColor = "@android:color/background_dark" /> < Button android:id = "@+id/second_activity_next_button" android:layout_width = "90dp" android:layout_height = "40dp" android:layout_marginTop = "200dp" android:layout_marginLeft = "200dp" android:text = "Next" android:textStyle = "bold" android:textColor = "@android:color/background_dark" android:textSize = "15sp" /> < Button android:id = "@+id/second_activity_previous_button" android:layout_width = "110dp" android:layout_height = "40dp" android:layout_marginTop = "200dp" android:layout_marginLeft = "50dp" android:text = "previous" android:textStyle = "bold" android:textColor = "@android:color/background_dark" android:textSize = "15sp" /> </ RelativeLayout > |
SecondActivity.java
package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.content.Intent; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { // define the global variable TextView question2; // Add button Move to next Activity and previous Activity Button next_button, previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_second); // by ID we can use each component which id is assign in xml file // use findViewById() to get the both Button and textview next_button = (Button)findViewById(R.id.second_activity_next_button); previous_button = (Button)findViewById(R.id.second_activity_previous_button); question2 = (TextView)findViewById(R.id.question2_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question2.setText( "Q 2 - What is ADB in android?
" + "
" + "Ans- Android Debug Bridge" ); // Add_button add clicklistener next_button.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called ThirdActivity with the following code: Intent intent = new Intent(SecondActivity. this , ThirdActivity. class ); // start the activity connect to the specified class startActivity(intent); } }); // Add_button add clicklistener previous_button.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called oneActivity with the following code: Intent intent = new Intent(SecondActivity. this , Oneactivity. class ); // start the activity connect to the specified class startActivity(intent); } }); } } |
Примечание. Здесь мы добавляем только кнопку «Далее» и текстовое поле для сообщения.
Полный код ThirdActivity.java или activity_third.xml третьего действия приведен ниже.
activity_third.xml
<? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = "org.geeksforgeeks.navedmalik.multiplescreenapp.ThirdActivity" > < TextView android:id = "@+id/question3_id" android:layout_marginTop = "60dp" android:layout_marginLeft = "30dp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textStyle = "bold" android:textColor = "@android:color/background_dark" /> < Button android:id = "@+id/third_activity_previous_button" android:layout_width = "110dp" android:layout_height = "40dp" android:layout_marginTop = "200dp" android:layout_marginLeft = "100dp" android:text = "previous" android:textStyle = "bold" android:textColor = "@android:color/background_dark" android:textSize = "15sp" /> </ RelativeLayout > |
ThirdActivity.java
package org.geeksforgeeks.navedmalik.multiplescreenapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.content.Intent; import android.widget.TextView; public class ThirdActivity extends AppCompatActivity { // define the global variable TextView question3; // Add button Move previous activity Button previous_button; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_third); // by ID we can use each component which id is assign in xml file // use findViewById() to get the Button and textview. previous_button = (Button)findViewById(R.id.third_activity_previous_button); question3 = (TextView)findViewById(R.id.question3_id); // In question1 get the TextView use by findViewById() // In TextView set question Answer for message question3.setText( "Q 3 - How to store heavy structured data in android?
" + "
" + "Ans- SQlite database" ); // Add_button add clicklistener previous_button.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // Intents are objects of the android.content.Intent type. Your code can send them // to the Android system defining the components you are targeting. // Intent to start an activity called SecondActivity with the following code: Intent intent = new Intent(ThirdActivity. this , SecondActivity. class ); // start the activity connect to the specified class startActivity(intent); } }); } } |
Выход: