NestedScrollView en Android con ejemplo

ScrollView NestedScrollView se usa cuando se necesita una vista de desplazamiento dentro de otra vista de desplazamiento. Ha visto esto en muchas aplicaciones, por ejemplo, cuando abrimos un archivo pdf y cuando llegamos al final del PDF hay un anuncio debajo del archivo pdf. Aquí es donde entra en juego NestedScrollView . Vamos a NestedScrollView en Android tomando un ejemplo.

Ejemplo

Paso 1: Creación de un nuevo proyecto

Para crear un nuevo proyecto en Android Studio, consulte Cómo crear/iniciar un nuevo proyecto en Android Studio . Tenga en cuenta que elija Java como lenguaje aunque vamos a implementar este proyecto en lenguaje Java.

Paso 2: antes de ir a la sección de codificación, primero haga una tarea previa

  • Vaya a la aplicación -> res -> valores -> strings.xml y agregue dos strings de texto aleatorio dentro del archivo strings.xml para mostrar esas strings en el archivo activity_main.xml .

XML

<resources>
    <string name="app_name">GFG | NestedScrollView </string>
    <string name="random_text_1">
        Hadoop is a data processing tool used to process large size data over distributed
        commodity hardware. The trend of Big Data Hadoop market is on the boom and it’s
          not showing any kind of deceleration in its growth. Today, industries are capable
          of storing all the data generated at their business at an affordable price just
          because of Hadoop. Hadoop helps the industry to know their customer’s behavior,
          customers buying priorities i.e. what they loved the most, and click patterns,
          etc. Hadoop provides personalized recommendations and personalizes ad targeting
          features. Companies are generating thousands of petabytes of data every day so the
          demand for Big Data professionals is very high. Even after a few years,
          Hadoop will be considered as the must-learn skill for the data-scientist
          and Big Data Technology. Companies are investing big in it and it will become
          an in-demand skill in the future. Hadoop provides personalized recommendations
        and personalizes ad targeting
          features. Companies are generating thousands of petabytes of data every day so the
          demand for Big Data professionals is very high. Even after a few years,
          Hadoop will be considered as the must-learn skill for the data-scientist
          and Big Data Technology. Companies are investing big in it and it will become
          an in-demand skill in the future.
    </string>
    <string name="random_text_2">
          Humans are coming closer to the internet at a very fast rate. It means that the
          volume of data Industries is gathering will increase as time passes because of
          more users. Industry’s are gradually analyzing the need for this useful information
          they are getting from their users. It is for sure that the data always tends to
          an increasing pattern so the company’s are eventually acquiring professionals
          skilled with Big Data Technologies. According to NASSCOM, India’s Big Data
          Market will reach 16 billion USD by 2025 from 2 billion USD. The growth of smart
          devices in India is growing at a very huge rate that will cause growth in the
          Big Data Market. Since Big Data is growing the demand for Big Data professionals
          will be high.  Hadoop provides personalized recommendations and personalizes ad targeting
          features. Companies are generating thousands of petabytes of data every day so the
          demand for Big Data professionals is very high. Even after a few years,
          Hadoop will be considered as the must-learn skill for the data-scientist
          and Big Data Technology. Companies are investing big in it and it will become
          an in-demand skill in the future.
    </string>
  
</resources>

Paso 3: Diseño de la interfaz de usuario 

En el archivo activity_main.xml agregue NestedScrollView y dentro de NestedScrollView agregue un LinearLayout y dentro de LinearLayout agregue dos TextView para mostrar las strings que se crean dentro del archivo strings.xml y un botón entre TextView. Aquí está el código para activity_main.xml expediente. Se pueden agregar tantas vistas dentro del LinearLayout de NestedScrollView

XML

<?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"
    tools:context=".MainActivity">
  
    <!-- Nested Scroll view -->
    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  
        <!-- Linear layout to contain 2 text view and button -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
  
            <!-- showing random text 1 from strings.xml file -->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/random_text_1" />
  
            <!-- simple button -->
            <Button
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="@color/colorPrimary"
                android:text="Nested Scroll View "
                android:textColor="#ffffff"
                android:textSize="32dp" />
  
            <!-- showing random text 2 from strings.xml file -->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/random_text_2" />
              
        </LinearLayout>
          
    </androidx.core.widget.NestedScrollView>
  
</RelativeLayout>

Paso 4: trabajar con el archivo MainActivity.java

No hay nada que hacer con el archivo MainActivity.java , así que manténgalo como está.

Java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Salida: ejecutar en el emulador 

Recursos:

  • Descargar proyecto completo desde Github
  • Download the Apk file

Publicación traducida automáticamente

Artículo escrito por onlyklohan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *