扣丁学堂笔记第04天基础UI组件(二)

1.Spinner

Spinner下拉列表提供一个快速的方法从一组选择一个值。在默认状态下Spinner显示当前的值。

添加静态列表值(不能动态加载):先在string中添加一个数组<array name="city"></array>,再往array中添加默认的城市选项,<item>北京</item><item>上海</item><item>广州</item><item>深圳</item><item>厦门</item>,最后往activity_main中添加一行代码:android:entries="@array/city"完成绑定


添加动态数据(在代码中编辑)

看了视频里的ArrayAdapter参数有四个,自己写了三个也可以,一直很纠结textViewResourceId到底是R.layout还是R.id,看了官方doc才明白都是可能的,看具体的方法

扣丁学堂笔记第04天基础UI组件(二)_第1张图片

 String[] roles ={"管理员","VIP会员","普通会员","游客"};
        //方式一:创建一个ArrayAdapter 参数(三个):上下文,布局ID,数据  或者参数(四个):上下文,布局ID,显示列表里的组件ID,数据
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, roles);
        //方式二:调用ArrayAdapter的createFromResource()方法,参数:上下文,数据,布局
        ArrayAdapter adapter2 = ArrayAdapter.createFromResource(this,R.array.city, android.R.layout.simple_spinner_dropdown_item);
        spinner_role.setAdapter(adapter2);


2.AutoCompleteTextView

如果你想为用户提供建议类型,可以使用EditText的子类AutoCompleteTextView,该组件可以根据用户输入的关键字来匹配可能满足用户需求的列表选项


在values文件夹中新建一个arrays.xml,在里面添加城市item,在activity_main.xml中 android:completionThreshold="1"表示当用户输入一个字符就开始匹配关键字,然后采用createFromResource方法来显示列表

 autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.city_name, android.R.layout.simple_spinner_dropdown_item);
        autoCompleteTextView.setAdapter(adapter);
 
 

3.ProgressBar
ProgressBar有两种显示方式:一是表盘形式(小、中(默认)、大),二是条形填充形式。在layout定义时,需要通过style属性类来设施展示方式
基本属性的使用
android:max="100"设置进度条的最大值
android:progress=“50”设置当前进度条显示值
android:secondaryProgress="true"设置第二进度条进度值(如视频缓冲进度条)
android:progressBarStyle默认进度条样式
android:progressBarStyleHorizontal水平样式
重要方法
getMax()返回进度条范围的上限
getProgress()返回当前进度值
getSecondaryProgress()返回第二进度条进度值
incrementProgressBy(int diff)指定增加的进度,即步长
isindeterminate()进度条是否在不确定模式下
setIndeterminate(boolean indeterminate)设置不确定模式
setVisibility()设置进度条是否可视


对话框与标题进度条

标题进度条
设置进度条标题(该方法必须在setContentView之前):requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
显示标题进度条:setProgressBarIndeterminateVisibility(true)

对话框

button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ProgressDialog dialog = new ProgressDialog(MainActivity.this);
				dialog.setMax(100);
				dialog.setProgress(30);
				dialog.incrementProgressBy(10);
				dialog.setTitle("下载对话框");
				dialog.setMessage("正在下载中...");
				dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				dialog.show();
			}
		});


自定义进度条

通过一个图片来自定义进度条

1.在res/drawable添加layer_list

2.设置ProgressBar的android:indeterminateDrawable属性

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <rotate android:fromDegrees="0"
            android:toDegrees="360"
            android:pivotX="50"
            android:pivotY="50"
            android:drawable="@drawable/progressbar"/>
    </item>

</layer-list>


android:indeterminateDrawable="@drawable/progress_bg"


4.AlertDialog

提示消息

实现步骤:

1.创建一个对话框的构造者AlertDialog.Builder builder = new AlertDialog(this);

2.调用它的setTitle()、setMessage()、setIcon()、setPositiveButton(字符串,监听器)、setNegativeButton(字符串,监听器DialogInterface.OnClickListener())、setNeutralButton(字符串,监听器);

3.创建一个对话框AlertDialog dialog = builder.create();dialog.show()或者简写成builder.show()

public void dialog1(View v){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("提示");
    	builder.setMessage("你有女朋友吗?");
    	builder.setIcon(R.drawable.ic_launcher);
    	builder.setPositiveButton("有", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, "你可以走了",Toast.LENGTH_SHORT).show();	
			}
		});
    	builder.setNegativeButton("没有", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, "欢迎来到单身俱乐部",Toast.LENGTH_SHORT).show();	
			}
		});
    	builder.setNeutralButton("隐藏", new DialogInterface.OnClickListener() {
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
	Toast.makeText(MainActivity.this, "无所谓",Toast.LENGTH_SHORT).show();	
	}
});
    	builder.show();
    }


选项列表与多选列表对话框

列表对话框

扣丁学堂笔记第04天基础UI组件(二)_第2张图片

实现步骤:

1.创建一个对话框的构造者,同上;

2.构造名为items的String数组;

3.调用builder的setItems(items,监听器)(注:如果使用内部类构造监听事件,构造数组要加上final关键字),监听事件的代码使用toast提示文本内容,Toast.makeText第二个参数即显示的内容可写成:items[which];

4.builder.show()

 public void dialog2(View v){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("请选择一个平台");
    	final String[] items = {"Android","IOS","Windows Phone"};
    	builder.setItems(items, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();	
			}
		});
    	builder.show();
    }

多选列表对话框
扣丁学堂笔记第04天基础UI组件(二)_第3张图片
实现步骤:
1.同上;
2.同上;
3.创建一个ArrayList列表:final ArrayList<String> list = new ArrayList<String>();
4.调用builder的setMultiChoiceItems(items,null,new DialogInterface.OnMultiChoiceClickListener()),在Onclick方法中添加如下逻辑:如果isChecked,list.add(items[which]),否则:list.remove(items[which]);
5.添加一个setPositiveButton,在OnClick中添加如下逻辑:Toast.makeText(MainActivity.this,list.toString(),Toast.LENGTH_SHORT).show(); dialog.dismiss();
6.添加一个setNegativeButton,在OnClick中添加如下逻辑:list.clear(); dialog.dismiss();
7.builder.show();
public void dialog3(View v){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("请选择一个平台");
    	final String[] items = {"Android","IOS","Windows Phone"};
    	final ArrayList<String> list = new ArrayList<String>();
    	builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked){
					list.add(items[which]);
				}else{
					list.remove(items[which]);
				}
			}
		});
    	
    	builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			Toast.makeText(MainActivity.this, list.toString(),Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			}
		});
    	builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				list.clear();
				dialog.dismiss();
			}
		});
    	builder.show();
    	
    }



多项单选与自定义自定义对话框

扣丁学堂笔记第04天基础UI组件(二)_第4张图片

实现步骤:

1.在OnClick方法外先定义一个result:String result = “Android”;

1.同上;

2.同上;

3.调用builder的setSingleChoiceItems(items,0(表示默认选中第一个选项),new DialogInterface.OnClickListener())

String result = "Android";
    public void dialog4(View v){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("请选择一个平台");
    	final String[] items = {"Android","IOS","Windows Phone"};
       	builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				result = items[which];
				Toast.makeText(MainActivity.this, "你选中了"+result, Toast.LENGTH_SHORT).show();
			}
		});
    	
    	builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			dialog.dismiss();
			}
		});
    	builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	builder.show();
    	
    }


自定义对话框

扣丁学堂笔记第04天基础UI组件(二)_第5张图片

实现步骤:

1.创建一个对话框的构造者builder;

2.设置标题;

3.自定义一个layout布局,添加两个EditText用于加载Username和Password,然后使用setView方法(注:API>=21即Android5.0)绑定自定义的布局。因此可以使用setView(View v)方法。在此之前添加如下代码:final View view = getLayoutInflater().inflate(R.layout.login_layout,null)(实例化布局)

4.在setPositiveButton中的OnClick方法里实例化两个EditText组件(view.findViewById);

5.将username和password转化为字符串:String username = editText_username.getText().toString()

public void dialog5(View v){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("登陆对话框");
    	builder.setIcon(R.drawable.ic_launcher);
    	final View view =getLayoutInflater().inflate(R.layout.login_layout, null);
    	builder.setView(view);
       
    	
    	builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				EditText editUsername = (EditText) view.findViewById(R.id.edit_username);
				EditText editPassword = (EditText) view.findViewById(R.id.edit_password);
				
				String username = editUsername.getText().toString();
				String password = editPassword.getText().toString();
				
				Toast.makeText(MainActivity.this, "用户名:"+username+",密码:"+password, Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			}
		});
    	builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
    	builder.show();
    	
    }



5.日期和时间

TimePickerDialog

实现步骤:

1.创建一个类继承DialogFragment(DialogFragment在android.app和v4包都有,如果要支持低版本设备可使用v4包):public (static) class TimePickerDialog{}

2.重写onCreateDialog方法,返回一个TimePickerDialog对象;具体代码:通过调用Calendar的getInstance()方法来获得Calendar的一个实例c,然后调用c.get(Calendar.HOUR_OF_DAY)和c.get(Calendar.MINUTE)来获取当前系统的时间

创建一个TimePickerDialog对象,参数(geActivity,this(监听事件,因为实现来onTImeSetListener()接口了,所以直接传入this),hour,minute,true(是否为24小时制))。然后return dialog;

3.实现TimePickerDialog的onTimeSetListener()接口来接收一个回调,当用户设置时间时。具体代码:在onTimeSet()添加如下代码来接收时间;:this.hour = hourOfDay; this.minute = minute;

4.在activity_main.xml中添加一个TextView来显示设置的时间,添加一个Button来弹出对话框。在onClick()方法里new一个TimePickerFragment:DialogFragment newFragment = new TimePickerFragment();再调用newFragment的show()方法,参数(getFragmentManager(),"TimePicker");

5.在MainActivity.java中自定义一个setTimeValue()方法,调用textView的setText方法来将时间显示在textView上;

6.在TimePickerFragment类中定义一个MainActivity的变量:private MainActivity mainActivity;

7.重写onCreate()方法,得到mainActivity的实例:mainActivity = getActivity();

8.在onTimeSet()方法中添加代码:mainActivity.setTimeValue(hour,minute);

9.别忘了实例化textView


TimePickerFragment.java代码

package com.example.timepickerdialogtest;

import java.util.Calendar;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements OnTimeSetListener{

	int hour;
	int minute;
	private MainActivity mainActivity;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getActivity();
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		hour = c.get(Calendar.HOUR_OF_DAY);
		minute = c.get(Calendar.MINUTE);
		TimePickerDialog dialog = new TimePickerDialog(getActivity(), this, hour, minute, true);
		return dialog;
	}
	@Override
	public void onTimeSet(TimePicker view, int hour, int minute) {
		// TODO Auto-generated method stub
		this.hour = hour;
		this.minute = minute;
		mainActivity.setTimeValue(hour, minute);
		
	}

}


MainActivity.java代码

package com.example.timepickerdialogtest;

import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {

	private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView1);
    }

    
    public void setTimeClick(View view){
    	DialogFragment newFragment = new TimePickerFragment();
    	newFragment.show(getFragmentManager(), "TimePicker");
    }
    
    public void setTimeValue(int hour,int minute){
    	textView.setText(hour+":"+minute);
    }
    
}

activity_main.xml代码

<TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="setTime" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="设置时间"
        android:onClick="setTimeClick" />


DatePickerDIalog

扣丁学堂笔记第04天基础UI组件(二)_第6张图片

实现步骤:

1.同上:public class DatePickerFragment extends DialogFragment implements onDateSetListener(){}

2.同上:c.get(Calendar.YEAR);c.get(Calendar.MONTH);c.get(Calendar.DAY_OF_MONTH)得到年月日;

3.自定义一个setDateValue()方法,将日期显示在textView组件上,注意month要加1;

4.在DatePickerFragment类中定义MainActivity变量,在onCreate方法里得到MainActivity的实例mainActivity;

5.在onDateSet方法里添加代码:mainActivity.setDatevalue()(注:本次year,month,day定义为局部变量,在onCreateDialog()里,与TimePickerFragment定义为全局变量不同,因此不用添加this.year = year等代码


DataPickerfragment.java代码

package com.example.datepickerdialogtest;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;

public class DatePickerFragment extends DialogFragment implements OnDateSetListener{

	private MainActivity mainActivity;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mainActivity = (MainActivity) getActivity();
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		
		DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
		return dialog;
	}
	
	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		// TODO Auto-generated method stub
		mainActivity.setDatevalue(year, monthOfYear, dayOfMonth);
	}

}

MainActivity.java代码

package com.example.datepickerdialogtest;

import android.app.Activity;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {

	
	private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.text_view);
    }

    public void setDatevalue(int year,int month,int day){
    	textView.setText(year+"年"+(month+1)+"月"+day+"日");
    }
    
    public void setDateClick(View view){
    	DialogFragment newFragment = new DatePickerFragment();
    	newFragment.show(getFragmentManager(), "DateFragment");
    }

}

activity_main.xml代码

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

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="setDate" />
    
    <Button 
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="setDateClick"
        android:text="设置日期"/>

</LinearLayout>



TimePicker和DatePicker

TimePicker

扣丁学堂笔记第04天基础UI组件(二)_第7张图片

实现步骤:

1.在xml文件中添加一个TimePicker,声明好相关属性;

2.实例化timePicker;

3.添加一个按钮用来保存选定的时间,在onClick事件里添加代码:int hour = timePicker.getCurrentHour(); int minute = timePicker.getCurrentMinute();然后toast出来


DatePicker

扣丁学堂笔记第04天基础UI组件(二)_第8张图片

实现步骤:

1.在xml文件中添加一个DatePicker,声明好相关属性;

2.实例化datePicker;

3.添加一个按钮用来保存选定的时间,在onClick事件里添加代码:int year = datePicker.getYear(); int month = datePicker.getMonth()+1; int day = datePicker.getDayOfMonth(); 然后toast出来



你可能感兴趣的:(扣丁学堂笔记第04天基础UI组件(二))