Android常用UI控件的使用(二)

ProgressBar进度条组件

参考博客

ProgressBar的常用属性

属性 介绍
style (进度条的样式,默认为圆形;用style="android:attr/progressBarStyleHorizontal"可以将进度条设为条状)
android:progress 进度条当前所处进度
android:max 进度条总进度

模拟进度条:
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"
    >

    <ProgressBar
        android:id="@+id/progressBar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java里的代码如下:

public class MainActivity extends AppCompatActivity{
    
    

    private ProgressBar progressBar;
    private int mProgress = 0;//当前进度
    private Handler handler;//消息处理对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
        progressBar = findViewById(R.id.progressBar);

        handler = 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(true){
    
    
                    mProgress = doWork();
                    Message m = new Message();
                    if(mProgress<100){
    
    
                        m.what = 0x111;//自定义消息代码
                        handler.sendMessage(m);//发送处理码
                    }else{
    
    
                        m.what = 0x110;
                        handler.sendMessage(m);
                        break;
                    }
                }
            }
            private int doWork(){
    
    
                mProgress += Math.random()*10;
                try {
    
    
                    Thread.sleep(200);//线程休眠200毫秒
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                return mProgress;
            }

        }).start();//开启线程
    }
}

SeekBar拖动条

拖动条是ProgressBar的子类耶,也就是ProgressBar的属性都可以用,而且他还有一个自己的属性就是:android:thumb,就是允许我们自定义滑块。

常用属性:

属性 介绍
android:max=”100” 滑动条的最大值
android:progress=”60” 滑动条的当前值
android:secondaryProgress=”70” 二级滑动条的进度
android:thumb = “@mipmap/sb_icon” 滑块的drawable

为拖动条添加监听:

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

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="10"
        android:progress="5"
        android:thumb="@mipmap/ico1" />
</LinearLayout>
public class MainActivity extends AppCompatActivity{
    
    

    private ProgressBar progressBar;
    private int mProgress = 0;//当前进度
    private Handler handler;//消息处理对象
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    
    
            //滑动滑块时触发
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    
    
                Toast.makeText(MainActivity.this,"进度改变"+progress,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星级评分条

XML属性 说明
android:isIndicator 设置该星级评分条是否允许用户改变(true为不允许修改)
android:numStars 设置该星机评分条总共有多少个星级
android:rating 设置该星级评分条默认的星级
android:stepSize 设置每次最少需要改变多少个星级

例:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="7"
        android:rating="3"
        />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交"
        android:layout_below="@+id/ratingBar"
        android:layout_alignParentRight="true"
        android:layout_marginRight="30dp"
        />
</RelativeLayout>
public class MainActivity extends AppCompatActivity{
    
    
    private RatingBar ratingBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);
        ratingBar = findViewById(R.id.ratingBar);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                float rating = ratingBar.getRating();//获取当前选中了多少颗星星
                Toast.makeText(MainActivity.this,"你当前选中了"+rating+"颗星",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

图像视图组件

常用属性:

属性 介绍
android:background 用于设置背景
android:foreground 用于设置前景,不受scaleType影响
android:adjustViewBounds 用于设置ImageView是否调整自己的边界来保持所显示图片的长宽比。
android:maxHeight 设置ImageView的最大高度,需要设置android:adjustViewBounds属性值为true,否则不起作用。
android:maxWidth 设置ImageView的最大宽度,需要设置android:adjustViewBounds属性值为true,否则不起作用
android:tint 用于为图片着色,其属性值可以是“#rgb”、“#argb”、“#rrggbb”或“#aarrggbb”表示的颜色值
android:scaleType 设置缩放方式
android:scaleType属性值:
(1)matrix(ImageView.ScaleType.MATRIX):从ImageView的左上角开始绘制原图,不缩放图片, 超过ImageView部分作裁剪处理;
(2)fitXY(ImageView.ScaleType.FIT_XY):对图片横向、纵向独立缩放,使得该图片完全适应该ImageView,图片的纵横比可能会改变
(3)fitStart(ImageView.ScaleType.FIT_START):保持纵横比缩放图片,直到该图片能完全显示在ImageView中,缩放完成后将该图片放在ImageView的左上角
(4)fitCenter(ImageView.ScaleType.FIT_CENTER):保持纵横比缩放图片,直到该图片能完全显示在ImageView中,缩放完成后将图片放在ImageView的中央
(5)fitEnd(ImageView.ScaleType.FIT_END):保持纵横比缩放图片,直到该图片能完全显示在ImageView中,缩放完成后将该图片放在ImageView的右下角
(6)center(ImageView.ScaleType.CENTER):把图片放在ImageView的中间,但不进行任何缩放
(7)centerCrop(ImageView.ScaleType.CENTER_CROP):保持纵横比缩放图片,以使得图片能完全覆盖ImageView
(8)centerInside(ImageView.ScaleType.CENTER_INSIDE):保持纵横比缩放图片,以使得ImageView能完全显示该图片

在这里插入图片描述

ImageSwitcher图片切换器

对于动画效果的支持,是因为它继承了ViewAnimator类,这个类中定义了两个属性,用来确定切入图片的动画效果和切出图片的动画效果:

  1. android:inAnimation:切入图片时的效果。
  2. android:outAnimation:切出图片时的效果。

实现手指滑动切换图片实例:

在这里插入图片描述

<?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"
    >
    <ImageSwitcher
        android:id="@+id/imageSwitcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity{
    
    
    private int[] arrayPicture = new int[]{
    
    
            R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
            R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,
            R.mipmap.img07,R.mipmap.img08,R.mipmap.img09
    };

    private int index;
    private ImageSwitcher imageSwitcher;
    private float touchDownX;//手指按下坐标
    private float touchUpx;//手指抬起坐标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);

        imageSwitcher = findViewById(R.id.imageSwitcher);
        //设置View工厂
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
    
    
            @Override
            public View makeView() {
    
    
                ImageView imageView = new ImageView(MainActivity.this);
                imageView.setImageResource(arrayPicture[index]);
                return imageView;
            }
        });
        //添加触摸事件监听器
        imageSwitcher.setOnTouchListener(new View.OnTouchListener() {
    
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
    
                //如果操作是按下
                if(event.getAction() == MotionEvent.ACTION_DOWN){
    
    
                    touchDownX = event.getX();
                    return true;
                }else if(event.getAction() == MotionEvent.ACTION_UP){
    
    
                    touchUpx = event.getX();
                    //判断手指向右滑还是向左滑
                    if(touchUpx-touchDownX > 100){
    
    
                        //向右滑动
                        index = index==0?arrayPicture.length-1:index-1;
                        //设置进入动画
                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_left));
                        //设置淡出动画
                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_out_right));
                        imageSwitcher.setImageResource(arrayPicture[index]);
                    }else if(touchDownX-touchUpx>100){
    
    
                        //从右向左滑
                        index = index==arrayPicture.length-1?0:index+1;
                        //设置进入动画
                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_in_right));
                        //设置淡出动画
                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this,R.anim.slide_out_left));
                        imageSwitcher.setImageResource(arrayPicture[index]);

                    }

                    return true;
                }
                return false;
            }
        });
    }
}

GridView网格视图

属性 介绍
android:horizontalSpacing 相关方法setHorizontalSpacing(int)。定义了两列之间的水平间隔
android:numColumns 相关方法setNumColumns(int)。定义了展示的列数。
android:verticalSpacing 相关方法setVerticalSpacing(int)。定义两行之间的垂直间隔
  • 利用适配器来显示图片:
    对于网格视图,无法用某一个属性来设置它显示哪些图片,需要使用适配器来设置。适配器是连接后端数据与前端显示的接口,是数据和UI组件之间的一个重要纽带。

Android中提供的4个常用的适配器实现类:

  1. ArrayAdapter :数组适配器,通常用于将数组的多个值包装成多个列表项。只能显示一行文字。
  2. SimpleAdapter :简单适配器,通常用于把List集合的多个值包装成多个列表项。可以自定义各种效果。
  3. SimpleCursorAdapter :将数据库的内容以列表的形式展示出来。
  4. BaseAdapter :基本适配器,通过这个适配器可以对各个列表项进行最大限度的定制。

参考博客

以SimpleAdapter为例实现九宫格图片:
在这里插入图片描述

  • 在res/layout目录下新建一个布局文件cell.xml,用于设置网格视图的一个单元格的内容:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
	<!-- 每个网格显示一张图片一个文本 -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="75dp"/>
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
<?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"
    >
    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:verticalSpacing="5dp"
        />
</LinearLayout>
public class MainActivity extends AppCompatActivity{
    
    
    private int[] picture = new int[]{
    
    
            R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
            R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,
            R.mipmap.img07,R.mipmap.img08,R.mipmap.img09
    };
    private String[] names = new String[]{
    
    
            "one","two","three",
            "four","five","six",
            "seven","eight","nine"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.one);

        GridView gridView = findViewById(R.id.gridView);
        List<Map<String,Object>> listitem = new ArrayList<Map<String,Object>>();
        for(int i = 0;i<picture.length;i++){
    
    
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("image",picture[i]);
            map.put("name",names[i]);
            listitem.add(map);
        }
        /*SimpleAdapter的参数说明
         * 第一个参数 表示访问整个android应用程序接口,基本上所有的组件都需要
         * 第二个参数表示生成一个Map(String ,Object)列表选项
         * 第三个参数表示界面布局的id  表示该文件作为列表项的组件
         * 第四个参数表示该Map对象的哪些key对应value来生成列表项
         * 第五个参数表示来填充的组件 Map对象key对应的资源一依次填充组件 顺序有对应关系
         * 注意的是map对象可以key可以找不到 但组件的必须要有资源填充  因为 找不到key也会返回null 其实就相当于给了一个null资源
         * 下面的程序中如果 new String[] { "name", "head", "desc","name" } new int[] {R.id.name,R.id.head,R.id.desc,R.id.head}
         * 这个head的组件会被name资源覆盖
         * */
        SimpleAdapter simpleAdapter = new SimpleAdapter(this,listitem,R.layout.cell,new String[]{
    
    "image","name"},new int[]{
    
    R.id.image,R.id.name});
        gridView.setAdapter(simpleAdapter);
    }
}

使用BaseAdapter适配器来显示图片:

  1. 同样需要准备9张图片,同时为GridView定义一个id
  2. 不需要控制网格视图中一个单元格布局的布局文件cell.xml
  3. 直接在Java文件中进行如下操作:
public class MainActivity extends AppCompatActivity{
    
    

    private int[] picture = new int[]{
    
    
            R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
            R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,
            R.mipmap.img07,R.mipmap.img08,R.mipmap.img09
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gridView = findViewById(R.id.gridView);
        gridView.setAdapter(new ImageAdapter(this));
    }

    public class ImageAdapter extends BaseAdapter{
    
    
        //定义一个上下文对象变量
        private Context mContext;
        //创建一个有参构造方法
        public ImageAdapter(Context c){
    
    
            mContext = c;
        }
        @Override
        public int getCount() {
    
    
            return picture.length; //将返回0改为返回图片资源数组的长度
        }
        @Override
        public Object getItem(int position) {
    
    
            return null;
        }
        @Override
        public long getItemId(int position) {
    
    
            return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
    
            ImageView imageView;//创建一个ImageView来显示网格视图中的一个图片,即网格视图的一个单元格
            if(convertView == null){
    
    
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(200,200));//设置单元格的大小
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);//设置图片缩放方式
            }else{
    
    
                imageView = (ImageView)convertView;
            }
            //将获取到的图片放在imageview中,position为当前需要显示图片的位置
            imageView.setImageResource(picture[position]);
            return imageView;
        }
    }
}

在这里插入图片描述

下拉列表框Spinner

属性:

android:entries :设置下拉列表框中的选项。取值为一个数组资源

  • 下拉列表框实例:
    在这里插入图片描述
  1. 创建一个数组资源文件
    在这里插入图片描述
    在这里插入图片描述
  2. 在activity_main.xml文件中,用Spinner标签来定义下拉列表框:
    在这里插入图片描述
  • 使用适配器来设置下拉列边框的选项内容并设置监听器:
<?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">
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

java代码操作:

public class MainActivity extends AppCompatActivity{
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spinner = findViewById(R.id.spinner);
        String[] ctype = new String[]{
    
    "全部","美术","音乐","体育"};
        //定义一个数组适配器。第一个参数为一个上下文对象;
        //第二个参数为android自带的下拉列表框的样式资源;
        //第三个参数为存放选项内容的Strings[]
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);
        adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        //为spinner设置选择事件监听器
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    
    
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    
    
                //获取选中的结果
                String result = parent.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
            }

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

            }
        });
    }
}

列表视图ListView

常用属性:

属性 介绍
android:divider 在列表条目之间显示的drawable或color
android:dividerHeight 用来指定divider的高度
android:entries 构成ListView的数组资源的引用。对于某些固定的资源,这个属性提供了比在程序中添加资源更加简便的方式
android:footerDividersEnabled 当设为false时,ListView将不会在各个footer之间绘制divider.默认为true。
android:headerDividersEnabled 当设为false时,ListView将不会在各个header之间绘制divider.默认为true。

activity_main.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">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:entries="@array/ctype"/>
</LinearLayout>

array.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ctype">
        <item>全部</item>
        <item>游戏</item>
        <item>电影</item>
        <item>图书</item>
    </string-array>
</resources>
public class MainActivity extends AppCompatActivity{
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
  • 在Java代码中通过适配器来指定列表项的内容:
public class MainActivity extends AppCompatActivity{
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.listView);
        String[] ctype = new String[]{
    
    "全部","图书","游戏","电视"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,ctype);
        listView.setAdapter(adapter);

    }
}

效果图:
在这里插入图片描述

  • 列表视图实例:
    在这里插入图片描述
<?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">
<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView"/>
</LinearLayout>

定义一个cell.xml布局文件

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

    <ImageView
        android:id="@+id/image"
        android:adjustViewBounds="true"
        android:layout_width="100dp"
        android:layout_height="75dp"/>
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"/>

</LinearLayout>

使用SimpleAdapte适配器实现:

public class MainActivity extends AppCompatActivity{
    
    

    private int[] imageid = new int[]{
    
    
            R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,
            R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,
            R.mipmap.img07,R.mipmap.img08,R.mipmap.img09
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.listView);
        String[] title = new String[]{
    
    "张三 ","李四 ","王五 ","张三 ","李四 ","王五","张三 ","李四 ","王五"};
        List<Map<String,Object>> listitem = new ArrayList<Map<String, Object>>();
        for(int i = 0;i<imageid.length;i++){
    
    
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("image",imageid[i]);
            map.put("title",title[i]);
            listitem.add(map);
        }
        //创建SimpleAdapter适配器对象
        SimpleAdapter adapter = new SimpleAdapter(this,listitem,R.layout.cell,new String[]{
    
    "title","image"},
        new int[]{
    
    R.id.title,R.id.image});
        listView.setAdapter(adapter);

        //添加监听器
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
    
                Map<String,Object> map = (Map<String,Object>)parent.getItemAtPosition(position);
                Toast.makeText(MainActivity.this,map.get("title").toString(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

滚动视图ScrollView

ScrollView用于设置垂直滚动条,HorizontalScrollView用于设置水平滚动条

  1. 在xml文件中添加滚动视图:

注意:

  • 垂直方向滚动时,layout_width要设置为match_parent,layout_height要设置为wrap_content*
  • 平方向滚动时,layout_width要设置为wrap_content,layout_height要设置为match_parent
  • 滚动视图节点下面必须且只能挂着一个子布局节点
  1. 在java代码中添加滚动视图:
public class MainActivity extends AppCompatActivity{
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取主布局管理器
        LinearLayout linearLayout1 = findViewById(R.id.linearLayout);
        //创建一个垂直线性布局管理器:
        LinearLayout linearLayout2 = new LinearLayout(MainActivity.this);
        //设置成垂直线性布局管理器
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        ScrollView scrollView = new ScrollView(MainActivity.this);
        //将滚动视图添加到跟布局管理器中
        linearLayout1.addView(scrollView);
        scrollView.addView(linearLayout2);
        ImageView imageView = new ImageView(MainActivity.this);
        imageView.setImageResource(R.mipmap.bg);
        linearLayout2.addView(imageView);
        TextView textView = new TextView(MainActivity.this);
        textView.setText(R.string.content);
        linearLayout2.addView(textView);
    }
}

选项卡

参考博客
Android开发中添加选项卡的步骤:
在这里插入图片描述

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<TabHost 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:orientation="vertical"
    android:id="@android:id/tabhost"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </TabWidget>
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
    </LinearLayout>

</TabHost>
<?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:id="@+id/left"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/biaoqing_left"/>

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/right"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/biaoqing_right"/>

</LinearLayout>

Java代码:

public class MainActivity extends AppCompatActivity{
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);//获取tabHost对象
        tabHost.setup();//初始化
        LayoutInflater inflater = LayoutInflater.from(this);
        inflater.inflate(R.layout.tab1,tabHost.getTabContentView());
        inflater.inflate(R.layout.tab2,tabHost.getTabContentView());
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("精选表情").setContent(R.id.left));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("投稿表情").setContent(R.id.right));
    }
}

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44630656/article/details/109518323