【Android基础学习之高级UI组件】

概要

本文主要的内容为笔者学习高级UI组件时所整理的笔记,主要包括以下几个方面。

1.常见进度条相关组件
2.视图类组件
3.框卡类组件

常见进度条相关组件

进度条(ProgressBar)

进度条样式选择方式
style属性值设定
1.可以通过主题属性进行设置(通过主题属性来改变进度条的样式)

style="@android:style/Widget.ProgressBar.Horizontal" //横屏进度条
style="@android:style/Widget.ProgressBar.Large" //大圆形进度条
style="@android:style/Widget.ProgressBar.Small" //小圆形进度条


2.Android设置好的样式资源进行设置

android:max = "100"  //设置最大进度为100
android:progress = "50" //设置当前进度为50

3.创建线程来循环获取当前的进度
线程逻辑
案例

//xml 文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@mipmap/xxl"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progress_bar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        />

</RelativeLayout>

相应的java逻辑代码

//java代码逻辑
package com.example.progressbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private ProgressBar progressBar; //定义进度条
    private int mProgress = 0; //用于记录完成进度
    private Handler mHandler; //定义用于消息处理的Handler对象

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //2.获取进度条对象
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        //3.实例化一个处理消息的类(android中不支持在主线程更新UI组件)
        mHandler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                //通过线程模拟耗时操作
                if (msg.what == 0x111) {
                    //更新进度
                    progressBar.setProgress(mProgress);
                } else {
                    Toast.makeText(MainActivity.this, "已加载完成", Toast.LENGTH_SHORT).show();
                    progressBar.setVisibility(View.GONE);
                }

            }
        };
        //创建并编写线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //使用while循环语句进行线程操作
                while (true) {
                    //设置do work方法该方法的返回值就是完成进度
                    mProgress = doWork();
                    //创建并实例化一个消息对象
                    Message message = new Message();
                    if (mProgress < 100) {
                        //设置消息代码(自定义0x111)用于区分消息值
                        message.what = 0x111;
                        //发送消息
                        mHandler.sendMessage(message);
                    } else {
                        //否则进度值已完成,设置相应完成代码(自定义0x110)
                        message.what = 0x110;
                        mHandler.sendMessage(message);
                        break;
                    }
                }
            }

            //do work的返回值为整形用于反馈进度
            private int doWork() {
                //进程每次增加任意值
                mProgress += Math.random() * 10;
                //线程休眠200毫秒,捕获异常
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return mProgress;
            }
            //开启线程
        }).start();
    }

}

拖动条(SeekBar)

其为进度条的子类,相关属性都能够正常使用。

android:thumb="@mipmap/QQ" //拖动条的样式可进行设置

//seekbar 状态改变监听器
SeekBar seekBar = findViewById(R.id.seekbar);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
	//状态改变时重写的方法
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                
    }
	//开始触摸时重写的方法
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }
	//停止触摸时重写的方法
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
    });

案例:
案例样式

//xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:src="@mipmap/saber" />

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="255"
        android:progress="255" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@mipmap/tk"
        android:paddingLeft="100dp"
        android:paddingTop="30dp"
        android:text="调节图片的透明度"
        android:textColor="@color/black"
        android:textSize="18dp" />

</LinearLayout>

java代码逻辑

package com.example.seekbar;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SeekBar seekBar;
    private ImageView image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.获取图片
        image = findViewById(R.id.image);
        //2.获取图片拖动条
        seekBar = findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                //此处的参数i就是进度progress
                image.setImageAlpha(i);
                Toast.makeText(MainActivity.this, "进度改变:"+i, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                Toast.makeText(MainActivity.this, "开始触摸", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Toast.makeText(MainActivity.this, "停止触摸", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

星级评分条(RatingBar)

特殊属性:

        android:numStars="8" //设置星星总数
        android:rating="5" //设置默认点亮几颗星
        android:stepSize="0.5"//默认是0.5每次增减的星星数量
        android:isIndicator="true"//设置星星是否能自由改变为true时不能改变      

实例:
星级评价

//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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <RatingBar
            android:id="@+id/ratingbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            android:rating="3"
            android:stepSize="0.5" />

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="发表评价" />


    </LinearLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

java逻辑代码

//java
package com.example.ratingbar;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Toast;

import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {
    private RatingBar ratingBar;

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.获取星级评分条
        ratingBar = findViewById(R.id.ratingbar);
        //2.获取按钮添加监听事件
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取选中几颗星
                float rating = ratingBar.getRating();
                Toast.makeText(MainActivity.this, "您打出了" + rating+"颗星的评价", Toast.LENGTH_SHORT).show();
            }
        });


    }
}

视图类组件

图像视图(ImageView)

属性:

android:scaleType="fitXY" //调整图片的缩放方式(也可以单独设置X/Y方向)

android:adjustViewBounds="true"//设置边界来保持图片长宽比(设置为true后就能设置图片最大的长宽)
//设置最大宽度和高度,通常与adjustViewBounds搭配使用
android:maxHeight="100dp" 
android:maxWidth="100dp"

android:tint="#77FFF000" //设置着色
tools:ignore="UseAppTint" //着色需要设置该属性否则会报错

android:screenOrientation="landscape"//设置横屏显示需要在菜单文件中的activity中添加该代码

实例:
横屏显示

//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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="170dp">


        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:adjustViewBounds="true"
            android:maxWidth="100dp"
            android:maxHeight="100dp"
            android:src="@drawable/saber" />

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:scaleType="fitEnd"
            android:src="@drawable/saber" />

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:scaleType="centerInside"
            android:src="@drawable/saber" />

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="5dp"
            android:src="@drawable/saber"
            android:tint="#77FF0000"
            tools:ignore="UseAppTint" />


    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

图像切换器(ImageSwitcher)

主要实现带动画效果的图片功能(相册翻看照片,选项框选择)
实例:
点击前
点击后
点击后

//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">

    <ImageSwitcher
        android:id="@+id/imageSwitcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

java逻辑代码

package com.example.imageswitcher;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class MainActivity extends AppCompatActivity {
    private ImageSwitcher imageSwitcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageSwitcher = findViewById(R.id.imageSwitcher);
        //淡出动画效果,两个参数(上下文参数,动画资源)
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_out));
        //进入动画效果,两个参数(上下文参数,动画资源)
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.fade_in));
        //设置视图工厂(参数通过匿名内部类来指定)
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                //实例化imageview对象
                ImageView imageView = new ImageView(MainActivity.this);
                //设置默认加载的图片
                imageView.setImageResource(R.drawable.xl);
                //返回视图
                return imageView;
            }
        });
        //当点击图像切换器的时候切换到另一个图片,为图像设置点击图像监听器
        imageSwitcher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //讲点击的图片进行强制类型转换,完成切换所运行的效果
                ((ImageSwitcher)view).setImageResource(R.drawable.saber);
            }
        });


    }
}

网格视图(GridView)

通常设置适配器来实现(java文件中添加适配器)
(适配器:后端数据与前端UI的重要纽带,是一个接口)
主要逻辑
Android主要提供了四种适配器:
1.ArrayAdapter(数组类适配器)
2.SmipleAdapter(简单适配器)
3.SmipleCursorAdapter(将数据库值以列表形式展现出来)
4.BaseAdapter(对各个列表项进行最大限度的定制)

思路:
1.在layout目录下创建cell.xml

//cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!--设置单元格的布局文件 -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="75dp" />


</LinearLayout>

相应的布局文件

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:layout_margin="3dp">

    </GridView>

</RelativeLayout>

java逻辑代码

package com.example.gridview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.GridView;
import android.widget.SimpleAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    //创建整形数组目的是为了储存资源id
    private int[] picture = new int[]{R.drawable.car, R.drawable.saber1,
            R.drawable.saber2, R.drawable.saber3, R.drawable.saber4,
            R.drawable.saber5, R.drawable.saber6, R.drawable.saber7};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.获取网格视图
        GridView gridView = findViewById(R.id.gridView);
        //2.创建LIST对象(是通过键值对保存的图像资源)
        List<Map<String, Object>> listItem = new ArrayList<Map<String, Object>>();
        //3.创建存储对象完成后需要通过for循环将Map添加到list中
        for (int i = 0; i < picture.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            //调用图片资源map的put方法
            map.put("image", picture[i]);
            listItem.add(map);
        }
        //创建一个适配器五个参数(上下文对象,list对象,布局文件,字符串数组map对象中的key,整形数组:布局文件中指定的组件id)
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,listItem,R.layout.cell,new String[]{"image"},new int[]{R.id.gridView});
        //为网格视图设置适配器
        gridView.setAdapter(simpleAdapter);
    }
}

列表视图(ListView)

属性:

android:entries="@array/type"//同下文的下拉列表框类似需要配置资源文件并通过该属性获取

//也可以通过适配器来指定
package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.创建数组适配器三个参数(上下文对象,外观样式,我们定义的字符串数组)
        String[] type = new String[]{"全部", "图书", "游戏", "电影", "音乐"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, type);
        //2.将ArrayAdapt对象与Listview相关联
        ListView listView = (ListView) findViewById(R.id.listview);
        listView.setAdapter(adapter);
    }
}

实例:
样例
1.每个选项的样式定制:

//people.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:maxWidth="72dp"
        android:maxHeight="72dp"
        android:paddingTop="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp" />

</LinearLayout>

2.页面整体布局:

//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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/top" />


        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="400dp">

        </ListView>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/bottom" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

3.java主代码逻辑

package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.创建整型数组目的是为了保存资源id
        int[] imageId = new int[]{R.drawable.saber_1,R.drawable.saber_2,
                R.drawable.saber_3,R.drawable.saber_4, R.drawable.car,};
        //2.创建字符串数组用于指定列表项中的文字
        String[] title = new String[]{"小明","纸鸢","大壮","傻柱","大波浪"};
        //3.创建list对象<map>键值对
        List<Map<String,Object>> listItem = new ArrayList<Map<String,Object>>();
        //4.通过for循环将图片和对应文字放进map列表当中
        for (int i = 0; i < imageId.length; i++) {
            //定义map对象对他进行初始化
            Map<String,Object> map = new HashMap<String,Object>();
            //将图片ID和对应的文字保存到Map对象中
            map.put("image",imageId[i]);
            map.put("name",title[i]);
            //将map对象保存到list当中
            listItem.add(map);
        }
        //5.创建SimpleAdapt适配器5个参数(上下文,list对象,我们编写的布局文件,map对象中的两个键,我们编写的布局文件中对应的id)
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,listItem,R.layout.people
                ,new String[]{"name","image"},new int[]{R.id.title,R.id.image});
        //6.获取listview
        ListView listView = findViewById(R.id.listview);
        //7.将适配器与列表视图关联
        listView.setAdapter(simpleAdapter);
        //8.为listview添加对应的监听器获取对应选中项的值
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map<String,Object>map =(Map<String,Object>)adapterView.getItemAtPosition(i);
                Toast.makeText(MainActivity.this, map.get("name").toString(), Toast.LENGTH_LONG).show();
            }
        });


    }
}

滚动视图(ScrollView/HorizontalScrollView)

添加滚动视图的两种方法:

注意:一个滑动视图只能放一个组件,如果想要放多个组件需要添加布局管理器将其括起来

//添加滚动视图的方法1(xml文件添加):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/content"
                android:textSize="20sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/content"
                android:textSize="20sp" />


        </LinearLayout>
    </HorizontalScrollView>


</RelativeLayout>

//添加滚动视图的方法2(java文件添加):
//1.使用构造方法ScrollView(Content c)创建滚动视图(参数是上下文对象)
//2.应用addView()方法添加组件到滚动视图中。
//3.将滚动视图添加到布局管理器中。

实例:
滚动视图

//xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    tools:context=".MainActivity">


</LinearLayout>



//Java逻辑
package com.example.scrollview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取根布局管理器
        LinearLayout ll =(LinearLayout)findViewById(R.id.ll);
        //创建布局管理器
        LinearLayout ll2 = new LinearLayout(this);
        //1.将布局管理器设置成垂直的样式(常量)
        ll2.setOrientation(LinearLayout.VERTICAL);
        //2.创建滚动视图
        ScrollView scrollView = new ScrollView(MainActivity.this);
        //3.将滚动视图添加到根布局管理器
        ll.addView(scrollView);
        //4.将后添加的布局添加到根布局管理器
        scrollView.addView(ll2);
        //5.为第二个垂直线性管理器添加视图
        ImageView imageView = new ImageView(MainActivity.this);
        imageView.setImageResource(R.drawable.saber1);
        //6.将图像视图添加到垂直的线性管理器ll2中
        ll2.addView(imageView);
        //7.创建文本框组件并添加
        TextView textView = new TextView(MainActivity.this);
        textView.setText(R.string.saber_introduction);
        ll2.addView(textView);

    }
}

框类组件

下拉列表框(Spinner)

属性:
方案1:android:entries=“” //指定下拉列表项,属性值是数组资源

//使用数组资源文件需要提前创建XML文件res/values/xml/new 一个Values_XML_File文件
//该文件中的资源文件为
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="type">
        <item>全部</item>
        <item>电影</item>
        <item>音乐</item>
        <item>游戏</item>
    </string-array>
</resources>

方案二:使用适配器网络进行配置

//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">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Spinner>

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

java逻辑代码

//实现适配器
package com.example.spinner;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.定义字符串数组type
        String[] type = new String[]{"全部","美术","音乐","体育"};
        //2.设置数组适配器三个参数(上下文对象,列表项样式,我们定义的字符串数组)
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,type);
        //3.为适配器提供下拉式的选项样式(使用android自带的样式)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //4.将适配器与下拉列表框关联起来
        Spinner spinner = findViewById(R.id.spinner);
        spinner.setAdapter(adapter);
        //5.用spinner.getSelectedItem()获取选中的选项值转换为字符串输出
        String str = spinner.getSelectedItem().toString();
        Toast.makeText(this, "str", Toast.LENGTH_SHORT).show();
    }
}

实例:
实例
提前添加的arrays.xml文件

//资源文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="type">
        <item>全部</item>
        <item>电影/电视</item>
        <item>音乐</item>
        <item>图书</item>
        <item>小事</item>
        <item>活动</item>
        <item>用户</item>
        <item>小组</item>
        <item>群聊</item>
        <item>游戏</item>
    </string-array>
</resources>

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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:background="@drawable/saber">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:entries="@array/type">

        </Spinner>

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="搜索"
            android:textColor="#F8F8FF" />


    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java中的java核心代码

package com.example.spinner;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //1.获取spinner并添加选择列表项监听器
        spinner=findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //获取选择项的值(根据当前的索引位置来确定选中项的值),此处的i即为选中项的值。
                String result = adapterView.getItemAtPosition(i).toString();
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }
}

小结

本文是笔者学习UI组件的时候所整理的笔记,本文的优势是所有代码都经过笔者亲手敲击,请放心食用,有需要改进和补充的部分请各位指出!十分感谢!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值