Switching views in android

Switch

Switch — ещё один вид переключателей, который появился в Android 4.0 (API 14). Находится в разделах Commons и Buttons. Фактически, это замена немного устаревшего ToggleButton. В новых проектах лучше использовать Switch.

Компонент используется в том случае, когда нужно переключиться на противоположное состояние — да/нет, вкл./выкл., открыть/закрыть. В реальной жизни это выглядит следующим образом.

При добавлении компонента в макет студия рекомендует использовать использовать SwitchCompat или SwitchMaterial. Общий принцип работы у них одинаковый, отличия касаются дизайна.

Компонент представляет собой полоску с двумя состояниями и сопровождающим текстом. Переключиться можно сдвиганием ползунка или касанием экрана в области компонента (не только на самом ползунке, но и на сопровождающем тексте).

По умолчанию компонент находится в выключенном состоянии. Чтобы установить его в включённом состоянии на этапе разработки, используйте атрибут android:checked=»true».

Сопровождающий текст задаётся в атрибуте android:text. А текст на самом переключателе задаётся при помощи атрибутов android:textOn (методы getTextOn() и setTextOn()) и android:textOff (методы getTextOff() и setTextOff()). Обратите внимание, что сопровождающий текст может быть очень большим и положение самого переключателя относительно этого текста можно регулировать при помощи атрибута android:gravity (смотри пример ниже). Если сопровождающий текст вам не нужен, то не используйте атрибут android:text.

Момент переключения можно отслеживать при помощи слушателя CompoundButton.OnCheckedChangeListener.

SwitchCompat

Студия рекомендует использовать SwitchCompat. Явных отличий у него нет.

Для показа текста на кнопке переключателя установите в true значение атрибута app:showText.

Не забывайте, что данный компонент можно использовать только в активностях типа AppCompatActivity.

Вы можете задать свой стиль для SwitchCompat, добавив строки в styles.xml

Цвет дорожки, вдоль которой двигается ползунок, можно поменять также через стиль:

Источник

How to switch between Activities in Android

In Android user interface is displayed through an activity. In Android app development you might face situations where you need to switch between one Activity (Screen/View) to another. In this tutorial I will be discussing about switching between one Activity to another and sending data between activities.

Before getting into complete tutorial I am giving the code snippets for handling activities. Lets assume that our new Activity class name is SecondScreen.java

Opening new Activity

To open new activity following startActivity() or startActivityForResult() method will be used.

Sending parameters to new Activity

To send parameter to newly created activity putExtra() methos will be used.

Receiving parameters on new Activity

To receive parameters on newly created activity getStringExtra() method will be used.

Opening new Activity and expecting result

In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.

Sending result back to old activity when StartActivityForResult() is used

To close activity call finish() method

Add entry in AndroidManifest.xml

To run our application you should enter your new activity in AndroidManifest.xml file. Add new activity between tags

Let’s Start with a simple project

So now we have all the code snippets related to activities. In this tutorial i created two xml layouts(screen1.xml, screen2.xml) and two Acvities(FirstScreenActivity.java, SecondScreenActivity.java). The following diagram will give you an idea about the file structure you will be need in this tutorial.

Now lets start by creating a simple project.

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstScreenActivity.
2. Now you need to create user interface for the FirstScreenActivity.java
3. Create a new xml file in layout folder or rename the main.xml to screen1.xml
Right Click on Layout -> New -> Android XML file and name it as screen1.xml
4. Now insert the following code in screen1.xml to design a small layout. This layout contains simple form with a button.

5. Now open your FirstScreenActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

6. Create a class called SecondScreenActivity.java. Right Click on src/yourpackagefolder -> New -> Class and name it as SecondScreenActivity.java

7. Now we need interface for our Second Actvity. Create a new xml file and name it as screen2.xml.
Right Click on Layout -> New -> Android XML file and name it as screen2.xml. Insert the following code in screen2.xml.

8. Now open SecondScreenActivity.java and type the following code. Here we are simply reading the parameters and displaying them on to screen

9. Now everything is ready and before running your project make sure that you an entry of new activity name in AndroidManifest.xml file. Open you AndroidManifest.xml file and modify the code as below

10. Finally run your project by right clicking on your project folder -> Run As -> 1 Android Application. You can see the application is running by switching between screens. The below image is output screenshots of both xml files.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.

Источник

Create swipe views with tabs using ViewPager

Swipe views allow you to navigate between sibling screens, such as tabs, with a horizontal finger gesture, or swipe. This navigation pattern is also referred to as horizontal paging. This topic teaches you how to create a tab layout with swipe views for switching between tabs, along with how to show a title strip instead of tabs.

Implement Swipe Views

You can create swipe views using AndroidX’s ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project.

To set up your layout with ViewPager , add the element to your XML layout. For example, if each page in the swipe view should consume the entire layout, then your layout should look like this:

To insert child views that represent each page, you need to hook this layout to a PagerAdapter . You can choose between two kinds of built-in adapters:

  • FragmentPagerAdapter — Use this when navigating between a fixed, small number of sibling screens.
  • FragmentStatePagerAdapter — Use this when paging across an unknown number of pages. FragmentStatePagerAdapter optimizes memory usage by destroying fragments as the user navigates away.

As an example, here’s how you might use FragmentStatePagerAdapter to swipe across a collection of Fragment objects:

Kotlin

The following sections show how you can add tabs to help facilitate navigation between pages.

Add Tabs Using a TabLayout

A TabLayout provides a way to display tabs horizontally. When used together with a ViewPager , a TabLayout can provide a familiar interface for navigating between pages in a swipe view.

Figure 1: A TabLayout with four tabs.

To include a TabLayout in a ViewPager , add a element inside of the element, as shown below:

Next, use setupWithViewPager() to link the TabLayout to the ViewPager . The individual tabs in the TabLayout are automatically populated with the page titles from the PagerAdapter :

Kotlin

For additional design guidance for tab layouts, see the Material Design documentation for tabs.

Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.

Источник

How to switch between Activities in Android

When making your Android apps you may get to the point where you need to create multiple Activities for different screens within your app. When you have multiple Activities you will need a way to transition between them in a way that doesn’t break the back button functionality.

In order to switch between Activities in Android you will need to follow these steps:

  1. Create the Activities
  2. Add the Activities to the app’s Manifest
  3. Create an Intent referencing the Activity class you want to switch to
  4. Call the startActivity(Intent) method to switch to the Activity
  5. Create a back button on the new Activity and call the finish() method on an Activity when the back button is pressed

I have created sample code below also available on GitHub showing how to transition between Activities.

A video version of this tutorial is available on YouTube which I have also embedded below.

Transitioning Between Activities in Android

Create Two Activities

We will start by creating two Activities, FirstActivity and SecondActivity.

The FirstActivity will contain a ConstraintLayout with a TextView label showing “First Activity” and a Button with the text “Go to Second Activity”.

User Interface of the First Activity

The SecondActivity will contain a ConstraintLayout with a TextView label showing “Second Activity” and a Button with the text “Back to First Activity”.

Add Both Activities to the App Manifest

Ensure there is an activity entry for both Activities in the application section of the manifest file located at app/src/main/AndroidManifest.xml

Create the Intent and Start the Activity

Making the following changes to the FirstActivity class.

Add a new method called “switchActivities()”, inside this method we will create an Intent passing a parameters of the current activity and the new activity class. Then use the startActivity(Intent) method to passing the Intent that was just created.

Inside the onCreate method, add an OnClickListener to the Button used for switching the new Activity. When selected call the switchActivities() method.

Using the finish() method to preserve the back button functionality

Making the following changes to the SecondActivity class.

Inside the onCreate method, add an OnClickListener to the Button used for going back to the previous Activity. When selected call the finish() method will will remove the SecondActivity and take you back to the FirstActivity.

User Interface of the Second Activity

How can I pass data between Activities?

When switching between Activities you may need to pass data from the source Activity to the destination Activity.

This is possible by providing data to the Intent used to transition between Activities through the use of the putExtra(…) method.

Using the example above to pass data from the FirstActivity to the SecondActivity, use the putExtra(…) method inside the method for switching between Activities, to pass a message that includes a reference to the origin Activity.

Inside the SecondActivity class, add a TextView to display the result and inside the onCreate(…) method, call the getIntent() method and the getStringExtra(…) method on the Intent to retrieve the message and populate it into the result TextView.

What is an Intent in Android?

Intents are used in Android to request an action from other app components such as Activities, Services, Broadcast Receivers or Content Providers.

The main use cases for Intents are:

  1. Starting an activity
  2. Starting a service
  3. Delivering a broadcast

Intents can be Explicit or Implicit. Explicit intents explicit specify the application that will perform the action on the intent. Implicit are kept generic and request a general action to be performed which could be satisfied by a number of different apps.

Intent Filters are defined in the app’s manifest file to advise which actions from a Implicit Intent that it can handle.

Источник

Introduction to Android Views and ViewGroups

All the interaction of a user with the Android application is through the user interface(UI), hence it is very important to understand the basics about the User Interface of an android application. Here in this tutorial, we are going to cover about various Views and ViewGroups and will try to explain how they can be used to design the User Interface of an android application.

Views

View is the basic building block of UI(User Interface) in android. View refers to the android.view.View class, which is the super class for all the GUI components like TextView , ImageView , Button etc.

View class extends Object class and implements Drawable.Callback , KeyEvent.Callback and AccessibilityEventSource .

View can be considered as a rectangle on the screen that shows some type of content. It can be an image, a piece of text, a button or anything that an android application can display. The rectangle here is actually invisible, but every view occupies a rectangle shape.

The question that might be bothering you would be , what can be the size of this rectangle?

The answer is either we can set it manually, by specifying the exact size(with proper units) or by using some predefined values. These predefined values are match_parent and wrap_content .

match_parent means it will occupy the complete space available on the display of the device. Whereas, wrap_content means it will occupy only that much space as required for its content to display.

A View is also known as Widget in Android. Any visual(that we can see on screen) and interactive(with which user can interact with) is called a Widget.

XML syntax for creating a View

Now, as we have explained earlier as well, to draw anything in your android application, you will have to sepcify it in the design XML files. And to add functionality we will create Java files.

Every view in XML has the following format:

  • It always start with an angle bracket, followed by the View name. We will introduce you to various types of Views very soon.
  • Then we write attributes that will define how that view will look on the screen of the application along with a value for the attribute. Each view has its own attributes which we will discuss in the next few tutorials which will cover various typs of views.
  • In the end, it is closed by/>

So, every View subclass needs to follow this format so that it can appear on the screen of the app. And this format is nothing but default XML style. Right!

There are two attributes that are necessary for every View . These are: android:layout_height and android:layout_width .

These attributes define the size of the invisible rectangle that a view makes. Using these attributes we can easily control the size for every view in our android application.

Apart from the above mentioned attributes, attributes like gravity , layout_gravity , padding and margin are some other commonly used attributes.

Most commonly used Android View classes

Here we have some of the most commonly used android View classes:

Programmatic and Declarative Approach

To create/define a View or a ViewGroup in your android application, there are two possible ways:

    The Programmatic Approach: In this we define/create our Views in the Java source file. We will learn about this approach in details later, as of now here is a sample code to add a Button to our view.

So addView() is the function used to add any View to the UI and setLayoutParams() function is used to set the various attributes.

  • The Declarative Approach: In this we define the View and ViewGroups directly in the design XML files, like we will be doing in the next couple of tutorials where we will study about various commonly used views.
  • Источник

    Читайте также:  Тема шаринган для андроид
    Оцените статью