Android Advanced UI Components

Android Advanced UI Components

1. Progress bar ProgressBar

ProgressBar, The progress bar is divided into a long progress bar (used when the operation is time-consuming) and a circular progress bar (used when the operation is time-consuming). The default style is a circular progress bar.

Example of use:

<ProgressBar
      android:id="@+id/indeterminateBar"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      />
  • To use a long progress bar:

    1. Set styleproperties:style="@android:style/Widget.ProgressBar.Horizontal"

    2. Set the progress of the progress bar:android:progress="25"

      A bar progress bar indicating that the current progress is 25%.

      <ProgressBar
            android:id="@+id/determinateBar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:progress="25"/>
      

      By default, the maximum progress of the progress bar is 100, which can be android:maxmodified through attributes.

  • Basic use: Check whether the time-consuming operation is completed in another thread, update the progress bar when it is not completed; hide the progress bar when it is completed.

    insert image description here

  • Since Android does not support updating UI components in the main thread, the update progress bar should use the objects provided by Android Handleto send messages and update the UI

Example:

package com.mingrisoft;

import android.app.Activity;
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;


import java.util.logging.LogRecord;

public class MainActivity extends Activity {
    
    
    private ProgressBar horizonP;            //水平进度条
    private int mProgressStatus = 0;        //完成进度
    private Handler mHandler;            //声明一个用于处理消息的Handler类的对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN); //设置全屏显示
        horizonP = (ProgressBar) findViewById(R.id.progressBar1);    //获取水平进度条
        mHandler = new Handler() {
    
    
            @Override
            public void handleMessage(Message msg) {
    
    
                if (msg.what == 0x111) {
    
    
                    horizonP.setProgress(mProgressStatus);    //更新进度
                } else {
    
    
                    Toast.makeText(MainActivity.this, "耗时操作已经完成", Toast.LENGTH_SHORT).show();
                    horizonP.setVisibility(View.GONE);    //设置进度条不显示,并且不占用空间
                }
            }
        };
        new Thread(new Runnable() {
    
    
            public void run() {
    
    
                while (true) {
    
    
                    mProgressStatus = doWork();    //获取耗时操作完成的百分比
                    Message m = new Message();
                    if (mProgressStatus < 100) {
    
    
                        m.what = 0x111;
                        mHandler.sendMessage(m);    //发送信息
                    } else {
    
    
                        m.what = 0x110;
                        mHandler.sendMessage(m);    //发送消息
                        break;
                    }
                }

            }

            //模拟一个耗时操作
            private int doWork() {
    
    
                mProgressStatus += Math.random() * 10;    //改变完成进度
                try {
    
    
                    Thread.sleep(200);        //线程休眠200毫秒
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                return mProgressStatus;    //返回新的进度
            }
        }).start();    //开启一个线程
    }
}

2. Drag bar SeekBar

SeekBar, drag bar, is ProgressBara subclass of.

In addition to the inherited properties, there is a special property:

  • android:thumb

    Set the style of the "dot" on the drag bar.

Example of use:

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

        />

Example:

package com.mingrisoft;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SeekBar;

public class MainActivity extends AppCompatActivity {
    
    
   private ImageView image;          //定义图片
    private SeekBar seekBar;          //定义拖动条
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView) findViewById(R.id.image);    //获取图片
        seekBar = (SeekBar) findViewById(R.id.seekbar);    //获取拖动条
        //为拖动条设置监听事件
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    
    
            // 当拖动条的滑块位置发生改变时触发该方法
            @Override
            public void onProgressChanged(SeekBar arg0, int progress,
                                          boolean fromUser) {
    
    
                // 动态改变图片的透明度
                image.setImageAlpha(progress);
            }
            @Override
            public void onStartTrackingTouch(SeekBar bar) {
    
    
                // 开始触摸时执行
            }
            @Override
            public void onStopTrackingTouch(SeekBar bar) {
    
    
                // 停止触摸时执行
            }
        });
    }
}

3. Star rating bar RatingBar

RatingBar, The star rating bar is also ProgressBara subclass of , and the component width needs to be set to wrap_content.

Main attributes:

Attributes illustrate
android:isIndicator Whether it is non-interactive , the value is trueorfalse
android:numStars number of stars
android:rating set rating
android:stepSize The step size of the rating, the default is 0.5, so you can choose half a star

Example of use:

<!-- 星级评分条 -->
    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="0"
        android:layout_above="@+id/btn"
        android:layout_marginBottom="60dp"/>
  • <RatingBar>.setRatting(<int ratting>)You can use or <RatingBar>.getRatting(<int ratting>)to set or get the current rating in Java .

  • Use <RatingBar>.setOnRatingBarChangeListener()to set up monitoring.

4. Display image component ImageView

ImageView, to display the image.

Example of use:

<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/my_image"
         android:contentDescription="@string/my_image_description"
         />
 </LinearLayout>

Common attributes:

Attributes illustrate
android:maxHeight maximum height
android:maxWidth maximum width
android:adjustViewBounds Set to maintain the aspect ratio of the image and adjust the border of the View. To take effect maxHeightwith maxWidththe property, this property needs to be set totrue
android:scaleType ImageViewSize that controls how the image fits
android:src Set image resource
android:tint Colorize the image

5. Image switching display ImageSwitcher

ImageSwitcher, to switch the displayed picture.

Example of use:

<ImageSwitcher
    android:id="@+id/imageswitcher"
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  • For ImageSwichersettings Factory(used for ImageSwichermanufacture ImageView):<imageSwitcher>.setFactory()

  • For ImageSwichersetting touch listeners:imageSwitcher.setOnTouchListener()

  • Set image resources:<imageSwitcher>.setImageRecource(<int RecourceID>)

Example: Realize photo album (slide to switch pictures)

package com.mingrisoft;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class MainActivity extends Activity {
    
    
    private int[] arrayPictures = 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,
    };// 声明并初始化一个保存要显示图像ID的数组
    private ImageSwitcher imageSwitcher; // 声明一个图像切换器对象
    //要显示的图片在图片数组中的Index
    private int pictutureIndex;
    //左右滑动时手指按下的X坐标
    private float touchDownX;
    //左右滑动时手指松开的X坐标
    private float touchUpX;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏显示

        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher); // 获取图像切换器
        //为ImageSwicher设置Factory,用来为ImageSwicher制造ImageView
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
    
    
            @Override
            public View makeView() {
    
    
                ImageView imageView = new ImageView(MainActivity.this); // 实例化一个ImageView类的对象
                imageView.setImageResource(arrayPictures[pictutureIndex]);//根据id加载默认显示图片
                return imageView; // 返回imageView对象
            }
        });
        imageSwitcher.setOnTouchListener(new View.OnTouchListener() {
    
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
    
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
    
    
                    //取得左右滑动时手指按下的X坐标
                    touchDownX = event.getX();
                    return true;
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
    
    
                    //取得左右滑动时手指松开的X坐标
                    touchUpX = event.getX();
                    //从左往右,看下一张
                    if (touchUpX - touchDownX > 100) {
    
    
                        //取得当前要看的图片的index
                        pictutureIndex = pictutureIndex == 0 ? arrayPictures.length - 1 : pictutureIndex - 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(arrayPictures[pictutureIndex]);
                        //从右往左,看上一张
                    } else if (touchDownX - touchUpX > 100) {
    
    
                        //取得当前要看的图片index
                        pictutureIndex = pictutureIndex == arrayPictures.length - 1 ? 0 : pictutureIndex + 1;
                        //设置切换动画
                        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_out_left));
                        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.slide_in_right));
                        //设置要看的图片
                        imageSwitcher.setImageResource(arrayPictures[pictutureIndex]);
                    }
                    return true;
                }
                return false;
            }
        });
    }

}

6. Grid view component GridView

GridView, display components in a grid form, the data in the grid Adapteris transmitted to the UI interface through the back-end data, and the style is configured through a separate layout file

Adapter: The adapter is an important bridge between the back-end data and the UI interface. It is complex to set a View for each data in the data set.

insert image description here

Commonly used Adapter:

  • ArrayAdapter

    Array adapter, which wraps multiple values ​​of the array into multiple list items, and can only display one line of text

  • SmipleAdapter

    A simple adapter that wraps Listmultiple values ​​into list items and can customize various effects

  • SimpleCursorAdapter

    Wrap database data into list items

  • BaseAdapter

    Basic adapter, powerful customization

GirdViewMain attributes:

Attributes illustrate
android:columnWidth column width
android:gravity Arrangement in each cell
android:horizontalSpacing horizontal spacing
android:numColumns Number of columns
android:verticalSpacing vertical spacing
android:stretchMode Extension method

Example of use:

<!--网格布局-->
    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="100dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="5dp">
  • <GridView>.setAdapter(<Adapter adapter>):set upAdapter

Example:

package com.mingrisoft;

import android.app.Activity;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class MainActivity extends Activity {
    
    
    //显示的图片数组
    private Integer[] picture = {
    
    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, R.mipmap.img10, R.mipmap.img11,
            R.mipmap.img12,};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GridView gridView= (GridView) findViewById(R.id.gridView);  //获取布局文件中的GridView组件
        gridView.setAdapter(new ImageAdapter(this));                //调用ImageAdapter

    }
    //创建ImageAdapter
    public class ImageAdapter extends BaseAdapter{
    
    
        private Context mContext;  //获取上下文
        public ImageAdapter(Context c){
    
    
            mContext=c;
        }
        @Override
        public int getCount() {
    
    
            return picture.length;//图片数组的长度
        }

        @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;
            if(convertView==null){
    
            //判断传过来的值是否为空
                imageView=new ImageView(mContext);  //创建ImageView组件
                imageView.setLayoutParams(new GridView.LayoutParams(100, 90));   //为组件设置宽高
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);        //选择图片铺设方式

            }else{
    
    
                imageView= (ImageView) convertView;
            }
            imageView.setImageResource(picture[position]);    //将获取图片放到ImageView组件中
            return imageView; //返回ImageView
        }
    }
}


7. Drop-down list box Spinner

Spinner, to display the drop-down list.

Example of use:

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

arrayA resource file can be used xmlto define the data to be populated in this dropdown. res/valuesCreate a new file below array.xml, for example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>
</resources>

Then set the property android:entriesto array/planets_arra.

Of course, it can also Adapterbe set in the form of Java code

package com.mingrisoft;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);   //获取下拉列表
        /****************通过指定适配器的方式为选择列表框指定列表项********************/
//		方法一
//		String[] ctype=new String[]{"全部","电影","图书","唱片","小事","用户","小组","群聊","游戏","活动"}
//		ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ctype);
//		方法二
//		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
//				this, R.array.ctype,android.R.layout.simple_dropdown_item_1line);	//创建一个适配器
//
//		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 为适配器设置列表框下拉时的选项样式
//		spinner.setAdapter(adapter); // 将适配器与选择列表框关联

        /***************************************************************************/
        //为下拉列表创建监听事件
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) {
    
    

    }
});
    }
}

8. List ViewListView

ListView, the list is displayed.

Example of use:

<ListView
       android:id="@+id/list_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />
  • andoroid:entriesList items can be specified via attributes

  • Also via adapter:<ListView>.setAdapter()

Example:

package com.mingrisoft;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
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 Activity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listview = (ListView) findViewById(R.id.listview); // 获取列表视图
        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,
        }; // 定义并初始化保存图片id的数组
        String[] title = new String[]{
    
    "刘一", "陈二", "张三", "李四", "王五",
                "赵六", "孙七", "周八", "吴九"}; // 定义并初始化保存列表项文字的数组
        List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>(); // 创建一个list集合
        // 通过for循环将图片id和列表项文字放到Map中,并添加到list集合中
        for (int i = 0; i < imageId.length; i++) {
    
    
            Map<String, Object> map = new HashMap<String, Object>(); // 实例化Map对象
            map.put("image", imageId[i]);
            map.put("名字", title[i]);
            listItems.add(map); // 将map对象添加到List集合中
        }
        SimpleAdapter adapter = new SimpleAdapter(this, listItems,
                R.layout.main, new String[] {
    
     "名字", "image" }, new int[] {
    
    
                R.id.title, R.id.image }); // 创建SimpleAdapter
        listview.setAdapter(adapter); // 将适配器与ListView关联
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("名字").toString(),Toast.LENGTH_SHORT).show();


    }
});
    }
}


9. ScrollViewScrollView

ScrollVView, scroll view, scroll vertically (horizontally use: HorizontalScrollView).

Example of use:

<ScrollView
	android:layout_width="match_parent"
	andorid:layout_height="wrap_content">
    
</ScrollView>
  • There can only be one sub-label inside, so when you need multiple components, you need to use layout Layoutfor nesting.

Example:

package com.mingrisoft;

import android.support.v7.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 {
    
    
    LinearLayout linearLayout, linearLayout2;//定义linearLayout为默认布局管理器,linearLayout2为新建布局管理器
    ScrollView scrollView;//定义滚动视图组件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        linearLayout = (LinearLayout) findViewById(R.id.ll);//获取布局管理器
        
        linearLayout2 = new LinearLayout(MainActivity.this);//创建一个新的布局管理器
        linearLayout2.setOrientation(LinearLayout.VERTICAL);//设置为纵向排列
        
        scrollView = new ScrollView(MainActivity.this);//创建滚动视图组件
        scrollView.addView(linearLayout2);//滚动视图组件中添加新建布局
        
        linearLayout.addView(scrollView);//默认布局中添加滚动视图组件
        
        ImageView imageView = new ImageView(MainActivity.this);//创建ImageView组件
        imageView.setImageResource(R.mipmap.cidian);//ImagView添加图片
        
        TextView textView = new TextView(MainActivity.this);//创建TextView组件
        textView.setText(R.string.cidian);//TextView添加文字
        
        linearLayout2.addView(imageView);//新建布局中添加ImageView组件
        linearLayout2.addView(textView);//新建布局中添加TextView组件
    }
}

  • <ScrollView>.addView(): add layout

10. Tabs

Both multi-tab pages.

Add steps:

  1. TabHostAdd the , TabWidget, TabContent(using ) component in the layout file FrameLayout.

    1. TabHostUse a fixed value of id:@android:id/tabhost

    2. <TabHost>Add LinearLayouta layout manager to add TabWidget, TabContent.

    3. LinearLayoutIn layout management, add TabWidget, iduse fixed value:@android:id/tabs

    4. LinearLayoutIn layout management, add FrameLayouta layout manager and iduse a fixed value:@android:id/tabcontent

      Example of use:

      <?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:id="@android:id/tabhost"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.mingrisoft.MainActivity">
          <LinearLayout
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
              <TabWidget
                  android:id="@android:id/tabs"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"/>
              <FrameLayout
                  android:id="@android:id/tabcontent"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
              </FrameLayout>
          </LinearLayout>
      </TabHost>
      
  2. Write layout files for each tab.

  3. Get and initialize TabHostthe component.

    1. Get TabHost:

      tabHost = (TabHost) findViewById(android.R.id.tabhost);//获取TabHost对象
      
    2. Initialize TabHost:

       tabHost.setup();//初始化TabHost组件
      
  4. TabHostAdd tabs to objects.

    1. Declare LayoutInflaterthe object and load the layout resource:

      LayoutInflater inflater = LayoutInflater.from(this);    // 声明并实例化一个LayoutInflater对象
       inflater.inflate(<布局资源id,如R.layout.tab1>, tabHost.getTabContentView());
      
    2. add tab

      <tabHost>.addTab(tabHost.newTabSpec("<tab规范化名称,非空,如t>")
                .setIndicator("<标签名称>")
                .setContent(<布局id,如R.id.liL1>));
      

Guess you like

Origin blog.csdn.net/teolih/article/details/118679350