QRCodeTools.zip
1.可编解码二维码
2.二维码中间可嵌入logo
3.实现了win10环境下的批处理文件
4.可参考源码工程修改工具,实现更多的功能
GBK 汉字基本库 笔画 笔顺
GBK汉字库
1.整合6763个GB2312个汉字
2.整合GBK/3,GBK/4协议共21003个汉字
3.五笔,拼音,和汉字结构等基本属性
4.已生成了GBKHelper.jar包,可直接使用或修改源代码实现更多功能
示例程序:
long lasttick = System.currentTimeMillis();
GB2312Helper gb2312Helper = GB2312Helper.singleton();
String info1 = "测试汉字拼音和五笔";
CharacterRecord recs1[] = gb2312Helper.getRecords(info1);
String rlt1 = gb2312Helper.getPingyin(recs1);
long curtick = System.currentTimeMillis();
System.out.println("=======GB2312用时:=======" + (curtick - lasttick));
System.out.println(rlt1);
System.out.println("size=" + GB2312Helper.singleton().getRecordSize());
long lasttick2 = System.currentTimeMillis();
GBKHelper gbkHelper = GBKHelper.singleton();
String info2 = "测试汉字拼音和五笔 龍齏";
CharacterRecord recs2[] = gbkHelper.getRecords(info2);
String rlt2 = gbkHelper.getPingyin(recs2);
long curtick2 = System.currentTimeMillis();
System.out.println("=======GBK用时:=======" + (curtick2 - lasttick2));
System.out.println(rlt2);
System.out.println("size=" + GBKHelper.singleton().getRecordSize());
=======GB2312用时:=======281
ce4shi4han4zi4pin1yin1he2wu3bi3
size=6763
=======GBK用时:=======140
ce4shi4han4zi4pin1yin1he2wu3bi3 long2ji1
size=20923
GB2312 汉字基本库
1.根据给定汉字值得到汉字拼音,五笔,笔顺,和笔画数
2.要所给定汉字的索引值得到汉字拼音,五笔,笔顺,和笔画数
3.可直接导入GB2312Helper.jar包使用,或修改代码实现更多功能
示例
public static void main(String args[]) {
GB2312Helper helper = GB2312Helper.singleton();
GB2312Record record = helper.getRecord('我');
if (record != null) {
System.out.println(record.getValue() + " " + record.getPingyin() + " " + record.getBishun());
} else {
System.out.println("null");
}
String info = "测试汉字拼音和五笔";
GB2312Record rcds[] = helper.getRecords(info);
String pingyin = helper.getPingyin(rcds);
System.out.println(pingyin);
}
输出:
我 wo3 3121534
ce4shi4han4zi4pin1yin1he2wu3bi3
Java NIO 聊天室 JSwing
package com.ui.server;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ServerBootFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JPanel jp = new JPanel(new BorderLayout());
JPanel jp1 = new JPanel(new FlowLayout());
JScrollPane jsp1 = new JScrollPane();
JButton jbStart = new JButton("启动");
JButton jbEnd = new JButton("关闭");
JTextArea jtaState = new JTextArea(10, 25);
Font font = new Font("Serif", Font.BOLD, 18);
Color fore = Color.YELLOW;
Color back = new Color(81, 217, 251);
public ServerBootFrame(String title) {
super(title);
this.getContentPane().add(jp);
jp.add(jsp1, "Center");
jsp1.getViewport().add(jtaState);
jp.add(jp1, "South");
jp1.add(jbStart);
jp1.add(jbEnd);
jtaState.setFont(font);
jtaState.setForeground(fore);
jtaState.setBackground(back);
jp1.setBackground(back);
this.setResizable(false);
this.setLocation(250, 250);
}
public void showFrame() {
this.pack();
this.setVisible(true);
}
public void bootingServer(final BootEndInterface bt) {
this.jbStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.boot();
}
});
}
public void endingServer(final BootEndInterface ed) {
this.jbEnd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ed.end();
}
});
}
public void closeWindow(final BootEndInterface ed) {
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e1) {
ed.end();
}
});
}
public void appendStringTojtaState(String str) {
jtaState.append(str);
}
}
package com.ui.client;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
public class LoginFrame extends JFrame
{
JLabel jUserName=new JLabel("用户姓名:");
JLabel jUserPsd=new JLabel("用户密码:");
JTextField txtUserName=new JTextField("",10);
JPasswordField txtUserPsd=new JPasswordField(10);
JButton okButton=new JButton("确定");
JButton regButton=new JButton("注册");
JPanel jp=new JPanel(new GridLayout(2,1));
JPanel jp1=new JPanel(new FlowLayout(FlowLayout.CENTER));
JPanel jp2=new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel jp3=new JPanel(new FlowLayout());
Font f=new Font("Serif",Font.BOLD,15);
public LoginFrame()
{
super("用户登陆界面");
this.setLocation(250,250);
this.getContentPane().add(jp,"Center");
this.getContentPane().add(jp3,"South");
jp.add(jp1);jp.add(jp2);
jp1.add(jUserName);jp1.add(txtUserName);
jp2.add(jUserPsd);jp2.add(txtUserPsd);
jp3.add(okButton);jp3.add(regButton);
txtUserName.setFont(f);
txtUserPsd.setFont(f);
txtUserPsd.setEchoChar('x');
txtUserName.setToolTipText("请输入用户名");
txtUserPsd.setToolTipText("请输入用户密码");
okButton.addActionListener(new SolveButtonEvent(1));
regButton.addActionListener(new SolveButtonEvent(2));
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void showWindow()
{
this.pack();
this.setVisible(true);
}
public void closeWindow()
{
this.dispose();
}
public String getUserName()
{
return this.txtUserName.getText().trim();
}
public String getUserPassword()
{
return new String(this.txtUserPsd.getPassword());
}
class SolveButtonEvent implements ActionListener
{
int select=0;
public SolveButtonEvent(int select)
{
this.select=select;
}
public void actionPerformed(ActionEvent e)
{
//int x=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getX();
//int y=(int) LoginFrame.this.txtUserName.getLocationOnScreen().getY();
String userName=LoginFrame.this.getUserName();
String userPsd=LoginFrame.this.getUserPassword();
int nameLength=userName.length();
int psdLength=userPsd.length();
if(select==1)
{ if(nameLength>0 && psdLength>0 )
{
if(LoginFrame.this.query(userName,userPsd)==true)
{
LoginFrame.this.closeWindow();
//new Client();
}
else
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","错误!","用户名或密码错误.\n登陆失败");
md.showDialog();
}
}
else
{
if(nameLength==0)
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户名不能为空");
md.showDialog();
}
else if(psdLength==0)
{
MyDialog md=new MyDialog(LoginFrame.this,"提示窗口","提示","用户密码不能为空");
md.showDialog();
}
}
}
else if(select==2)
{
RegisterFrame rf=new RegisterFrame(LoginFrame.this);
rf.showWindow();
}
}
}
public boolean query(String userName,String userPsd)
{
Connection conn=null;
PreparedStatement psm=null;
ResultSet rs=null;
String sql="select * from user_manager where name=? and psd=?";
boolean result=false;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xdf","scott","tiger");
psm=conn.prepareStatement(sql);
psm.setString(1,userName);
psm.setString(2,userPsd);
rs=psm.executeQuery();
//rs结果集指向第一条记录的前一个位置
//如果第一条记录为空表示用户名或密码错误
if(rs.next()==true)
{
result=true;
this.closeWindow();
}
psm.close();
conn.close();
}
catch(ClassNotFoundException e1){ e1.printStackTrace(); }
catch(SQLException e2){ e2.printStackTrace(); }
catch(Exception e3){ e3.printStackTrace(); }
return result;
}
}
package com.nio.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import com.nio.user.ClientUser;
import com.nio.user.ClientUserManager;
import com.nio.user.UserData;
public class NIOClient {
private ClientUserManager cltManager = null;
//通道管理器
private Selector selector;
/**
* 获得一个Socket通道,并对该通道做一些初始化的工作
* @param ip 连接的服务器的ip
* @param port 连接的服务器的端口号
* @throws IOException
*/
public void initClient(String ip,int port) throws IOException {
cltManager = ClientUserManager.instance();
// 获得一个Socket通道
SocketChannel channel = SocketChannel.open();
// 设置通道为非阻塞
channel.configureBlocking(false);
// 获得一个通道管理器
this.selector = Selector.open();
// 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
//用channel.finishConnect();才能完成连接
channel.connect(new InetSocketAddress(ip,port));
//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。
channel.register(selector, SelectionKey.OP_CONNECT);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
* @throws IOException
* @throws InterruptedException
*/
@SuppressWarnings("unchecked")
public void listen() throws IOException, InterruptedException {
// 轮询访问selector
while (true) {
// 选择一组可以进行I/O操作的事件,放在selector中,客户端的该方法不会阻塞,
//这里和服务端的方法不一样,查看api注释可以知道,当至少一个通道被选中时,
//selector的wakeup方法被调用,方法返回,而对于客户端来说,通道一直是被选中的
selector.select();
// 获得selector中选中的项的迭代器
Iterator ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 连接事件发生
if (key.isConnectable()) {
SocketChannel channel = (SocketChannel) key
.channel();
System.out.println("channel client ?" + channel);
// 如果正在连接,则完成连接
if(channel.isConnectionPending()){
channel.finishConnect();
}
//设置成非阻塞
channel.configureBlocking(false);
//在这里可以给服务端发送信息哦
//channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes()));
//在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
//添加用户
UserData userData = new UserData();
userData.lineState = 1;
userData.channel = channel;
cltManager.addUser(userData);
//连接成功发送一个通知消息
UIClient.sendUserInfoMsg();
} else if (key.isReadable()) {
ClientUser cltUser = cltManager.getUser((SocketChannel)key.channel());
if (!cltUser.read()) {
key.channel().close();
}
}
//删除已选的key,以防重复处理
ite.remove();
}
}
}
}
package com.nio.server;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import com.nio.user.ServerUser;
import com.nio.user.ServerUserManager;
import com.nio.user.UserData;
import com.ui.server.BootEndInterface;
import com.ui.server.ServerBootFrame;
public class NIOServer implements BootEndInterface {
private ServerBootFrame serverFrame = new ServerBootFrame("服务器端");
private ServerUserManager userManager = null;
HashMap<String, String> hmClient = new HashMap<String, String>();
Vector<String> client = new Vector<String>();
int count = 0;
private static NIOServer nioServer = null;
public NIOServer() {
serverFrame.showFrame();
serverFrame.bootingServer(this);
serverFrame.endingServer(this);
serverFrame.closeWindow(this);
nioServer = this;
}
// 通道管理器
private Selector selector;
/**
* 获得一个ServerSocket通道,并对该通道做一些初始化的工作
*
* @param port
* 绑定的端口号
* @throws IOException
*/
public void initServer(int port) throws IOException {
serverFrame.appendStringTojtaState("服务器(NIO机制)启动中......\n");
// 获得一个ServerSocket通道
ServerSocketChannel serverChannel = ServerSocketChannel.open();
// 设置通道为非阻塞
serverChannel.configureBlocking(false);
// 将该通道对应的ServerSocket绑定到port端口
serverChannel.socket().bind(new InetSocketAddress(port));
// 获得一个通道管理器
this.selector = Selector.open();
// 将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
// 当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
//System.out.println("serverChannel 0?" + serverChannel);
}
/**
* 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
*
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void listen() throws IOException {
// System.out.println("服务端启动成功!");
serverFrame.appendStringTojtaState("服务器(NIO机制)启动成功......\n");
// 轮询访问selector
while (true) {
// 当注册的事件到达时,方法返回;否则,该方法会一直阻塞
selector.select();
// 获得selector中选中的项的迭代器,选中的项为注册的事件
Iterator<?> ite = this.selector.selectedKeys().iterator();
while (ite.hasNext()) {
SelectionKey key = (SelectionKey) ite.next();
// 客户端请求连接事件
if (key.isAcceptable()) {
ServerSocketChannel server = (ServerSocketChannel) key
.channel();
// 获得和客户端连接的通道
SocketChannel channel = server.accept();
System.out.println("channel A?" + channel);
// 设置成非阻塞
channel.configureBlocking(false);
// 在这里可以给客户端发送信息哦
// channel.write(ByteBuffer.wrap(new
// String("向客户端发送了一条信息").getBytes()));
// 在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
channel.register(this.selector, SelectionKey.OP_READ);
// 添加一个玩家对象
UserData userData = new UserData();
userData.lineState = 1;
userData.channel = channel;
userManager.addUser(userData);
} else if (key.isReadable()) {
ServerUser serverUser = userManager
.getUser((SocketChannel) key.channel());
// 读取数据失败
if (!serverUser.read()) {
serverUser.clean();
key.channel().close();
}
}
// 删除已选的key,以防重复处理
ite.remove();
}
}
}
/**
* 启动服务端测试
*
* @throws IOException
*/
public static void main(String[] args) throws IOException {
new NIOServer();
}
@Override
public void boot() {
userManager = ServerUserManager.instance();
userManager.initUsers();
serverFrame.appendStringTojtaState("创建玩家内存数据对象成功...\n");
new Thread(new Runnable() {
@Override
public void run() {
try {
NIOServer.this.initServer(5555);
NIOServer.this.listen();
} catch (Exception e) {
serverFrame.appendStringTojtaState("服务器启动失败......\n");
}
}
}).start();
//服务端主逻辑处理
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1);
userManager.run();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
@Override
public void end() {
if (selector != null) {
try {
selector.close();
selector = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.exit(0);
}
public void solveMsg(String message) {
try {
System.out.println(message);
// 对消息进行分析
String msg[] = message.split("#");
if (msg[0].equals("AddUser") == true) {
hmClient.put(msg[1], msg[2]);
sendUsersToOneUser(msg[1]);
if (likeThisName(msg[1]))// 如果出现同名用户,则在用户名后面添加数字来区分
{
msg[1] = msg[1] + count;
}
client.add(msg[1]);
serverFrame.appendStringTojtaState(msg[1] + "上线...\n");
sendMessageToAllUsers(
"AddUser" + "#" + msg[1] + "#" + hmClient.get(msg[1]),
msg[1]);
} else if (msg[0].equals("UserQuit") == true) {
sendMessageToAllUsers("UserQuit" + "#" + msg[1] + "#"
+ hmClient.get(msg[1]), msg[1]);
serverFrame.appendStringTojtaState(msg[1] + "离线...\n");
deleteKeyValue(msg[1]);
client.remove(msg[1]);
// 应该删除vecUser容器中的对应的Socket对象
} else if (msg[0].equals("Message") == true) { // 如果将消息发送给特定用户
if (msg[1].equals("One") == true) {
sendMessageToOneUser("Message" + "#" + msg[2] + "#"
+ msg[6], msg[4]);
} else// 将消息发送给全部用户
{
sendMessageToAllUsers("Message" + "#" + msg[2] + "#"
+ msg[4], msg[2]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessageToAllUsers(String msg, String notSendToThisUserName) throws UnsupportedEncodingException {
ServerUser lstUsers[] = userManager.getUsers();
for (int i = 0; i < lstUsers.length; i++) {
if (lstUsers[i].channel != null) {
String address = lockOut(""
+ lstUsers[i].channel.socket().getRemoteSocketAddress());
if ( !address.equals(hmClient.get(notSendToThisUserName)) ) {
lstUsers[i].write(msg.getBytes("utf-8"));
}
}
}
}
public void sendMessageToOneUser(String msg, String sendToThisUserName) throws UnsupportedEncodingException {
ServerUser lstUsers[] = userManager.getUsers();
for (int i = 0; i < lstUsers.length; i++) {
if (lstUsers[i].channel != null) {
String address = lockOut(""
+ lstUsers[i].channel.socket().getRemoteSocketAddress());
if ( address.equals(hmClient.get(sendToThisUserName)) ) {
lstUsers[i].write(msg.getBytes("utf-8"));
break;
}
}
}
}
// 方法完成将在线用户添给用户的下拉表中
public void sendUsersToOneUser(String newUserName) throws UnsupportedEncodingException {
Iterator<String> it = client.listIterator();
for (; it.hasNext();) {
String name = it.next();
String ipAndPort = hmClient.get(name);
sendMessageToOneUser("OnlyAddUser" + "#" + name + "#" + ipAndPort,
newUserName);
}
}
// 将键值对添加到hmClient哈希表中
public void createKeyValue(String userName, String socketAddress) {
hmClient.put(userName, socketAddress);
}
// 从哈希表中删除指定键值对(键为:userName);
public void deleteKeyValue(String userName) {
hmClient.remove(userName);
}
// 将字符串前面的斜杠去掉
public String lockOut(String socketAddress) {
return socketAddress.substring(1, socketAddress.length());
}
// 如果client容器中存放的用户名出现相似用户,则用户名后面添加一个数字
public boolean likeThisName(String thisName) {
count = 0;
for (Iterator it = client.listIterator(); it.hasNext();) {
String temp = (String) it.next();
if (temp.startsWith(thisName) == true) {
count++;
}
}
if (count > 0)
return true;
else
return false;
}
public static void handleMessage(String msg) {
// System.out.println("服务端收到信息:" + msg);
nioServer.solveMsg(msg);
}
}
JAVA NIO 聊天室程序
1.学习时的一个聊天室程序,将服务端改为NIO机制
2.支持多人同时在线局域网聊天
3.知识面:JSwing,NIO,消息包加密,解密,单列模式的线程安全机制等.
android 签名查看工具
签名查看工具:
1.在各个开发者平台上发布作用时,基本都需要应用的签名值,
MD5或SHA1值,用命令行查看时,多了很多无的用的字符如:“:”
此工具,指定一个文件和签名密码真接返回优化后的值
2.实现流程可参考源码项目
java 银行卡 验证 正则表达式使用
验证工具类:
1.银行卡验证
2.手机号码验证
3.邮箱,URL地址验证
AXMLPrinter源代码
1. AXMLPrinter在android 高版本下 生成的xml文件 反编译会报错 ArrayIndexOutOfBoundsException
2. AXMLPrinter2ME 处理了ArrayIndexOutOfBoundsException 异常
3. 提供官方源代码和AXMLPrinter2ME源代码
4. 此工具仅用于学习
android 蓝牙通信模块源码
用户通过Broadcast(广播)进行与后台通信模块Service进行通信(控制Service或者接收反馈信息)。以下是对应的广播Action类型。
服务器端Action列表:(同公用Action列表)
服务器与客户端公用Action列表:
ACTION_STOP_SERVICE:关闭后台服务。当程序退出或需要停止蓝牙服务时发送此广播
ACTION_DATA_TO_SERVICE:数据传送至后台Service。包含一个key为DATA的参数,该参数类型为实现了Serializable接口的类(该类为用户自己编写的数据实体类)。
ACTION_CONNECT_SUCCESS:连接成功。从后台Service发送出连接成功建立的广播。
ACTION_CONNECT_ERROR:连接错误。从后台Serivce发送出连接发生错误的广播。
ACTION_DATA_TO_GAME:从后台Service传送出数据。包含一个key为DATA的参数,该参数类型为实现了Serializable接口的类(该类为用户自己编写的数据实体类)。
客户端Action列表:
ACTION_START_DISCOVERY:开启蓝牙搜索。命令后台Service开始蓝牙搜索。
ACTION_SELECTED_DEVICE:选中的蓝牙设备。包含一个key为DEVICE的参数,该参数类型为BluetoothDevice(蓝牙设备类)。
用户需要从搜索到的蓝牙设备中选择服务器设备,选择设备后发送Broadcast,告知后台Service选择的蓝牙设备。
ACTION_FOUND_DEVICE:发现设备。后台Service进行搜索蓝牙设备过程中,每发现一个设备便会发送该Broadcast。
ACTION_NOT_FOUND_SERVER:未发现服务器设备。后台Service通过搜索并未发现可连接的蓝牙设备,发送此Broadcast。
android 地址 日期选择器
package com.demo.dtselector;
import com.custom.dtselector.dialog.DateSelectorDialog;
import com.custom.dtselector.dialog.DateSelectorDialog.OnSelectDateEvent;
import com.custom.dtselector.dialog.TimeSelectorDialog;
import com.custom.dtselector.dialog.TimeSelectorDialog.OnSelectTimeEvent;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DateTimeSelectorActivity extends Activity {
private Activity activity = null;
private DateSelectorDialog dateDialog = null;
private TimeSelectorDialog timeDialog = null;
private TextView txt_date_show = null;
private TextView txt_time_show = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datetime_main);
activity = this;
Button btnDate = (Button)findViewById(R.id.btn_date_selector);
btnDate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDateDialog();
}
});
Button btnTime = (Button)findViewById(R.id.btn_time_selector);
btnTime.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showTimeDialog();
}
});
txt_date_show = (TextView)findViewById(R.id.txt_date_show);
txt_time_show = (TextView)findViewById(R.id.txt_time_show);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.datetime_selector, menu);
return true;
}
private void showDateDialog() {
if (dateDialog == null) {
dateDialog = new DateSelectorDialog();
dateDialog.init(activity);
dateDialog.setOnSelectDateEvent(new OnSelectDateEvent(){
@Override
public void onSelectDateResult(int year, int month, int day) {
// TODO Auto-generated method stub
txt_date_show.setText(String.format("d-d-d",
year,month,day));
}
});
}
dateDialog.show();
}
private void showTimeDialog() {
if (timeDialog == null) {
timeDialog = new TimeSelectorDialog();
timeDialog.init(activity);
timeDialog.setOnSelectTimeEvent(new OnSelectTimeEvent(){
@Override
public void onSelectTimeResult(int hour, int minute, int second) {
// TODO Auto-generated method stub
txt_time_show.setText(String.format("d:d:d",
hour,minute,second));
}
});
} else {
timeDialog.update(null);
}
timeDialog.show();
}
}
android 百度地图 定位示例
1.需要在 http://developer.baidu.com/ 注册开发者(个人或公司)账号
2.需要申请Key
打开网址 http://developer.baidu.com/map/index.php
点击 创建应用,跟流程创建应用app
3.点击相关下载->一键下载
4.调用百度地图的APP 需要在 AndroidManifest.xml 添加
<application
android:name="baidumapsdk.demo.DemoApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
这里需要添加key,创建应用后,会有这个key
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="6t2yuIFylnRG7ECj1xHYuelY" />
.....
package com.obtk.mapdemo;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.app.Activity;
import com.obtk.mapdemo.R;
public class MapApiDemoActivity extends Activity implements
OnGetGeoCoderResultListener {
private MapView mMapView = null;
private BaiduMap mBaiduMap = null;
private GeoCoder mSearch = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SDK初始化
SDKInitializer.initialize(getApplicationContext());
//当前视图
setContentView(R.layout.activity_map_api_demo);
//创建地图对象
init();
final Button btn_location = (Button) findViewById(R.id.btn_location);
btn_location.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getLocation();
btn_location.setEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_map_api_demo, menu);
return true;
}
/**
* 初始化方法
*/
private void init() {
//mMapView = (MapView) findViewById(R.id.bmapview);
mMapView = new MapView(this, new BaiduMapOptions());
mBaiduMap = mMapView.getMap();
/**添加一个对象*/
RelativeLayout rlly_map = (RelativeLayout)findViewById(R.id.rlly_map);
rlly_map.addView(mMapView);
// 开启定位图层
mBaiduMap.setMyLocationEnabled(true);
//初始化搜索模块,注册事件监听
mSearch = GeoCoder.newInstance();
mSearch.setOnGetGeoCodeResultListener(this);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onDestroy() {
// 退出时销毁定位
mLocClient.stop();
// 关闭定位图层
mBaiduMap.setMyLocationEnabled(false);
mMapView.onDestroy();
mMapView = null;
super.onDestroy();
}
// 定位相关
LocationClient mLocClient;
public MyLocationListenner myListener = new MyLocationListenner();
private LocationMode mCurrentMode;
private boolean isFirstLoc = true;
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || mMapView == null)
return;
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
//此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
mBaiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
mBaiduMap.animateMapStatus(u);
}
String addr = location.getAddrStr();
if (addr != null) {
Log.i("Test", addr);
} else {
Log.i("Test","error");
}
double longitude = location.getLongitude();
double latitude = location.getLatitude();
if (longitude > 0 && latitude > 0) {
Log.i("Test",String.format("纬度:%f 经度:%f", latitude,longitude));
LatLng ptCenter = new LatLng(latitude,longitude);
// 反Geo搜索
mSearch.reverseGeoCode(new ReverseGeoCodeOption()
.location(ptCenter));
}
//停止定位
mLocClient.stop();
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
private void getLocation() {
// 定位初始化
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);//打开gps
option.setCoorType("bd09ll"); //设置坐标类型
option.setScanSpan(5000); //定位时间间隔
mLocClient.setLocOption(option);
mLocClient.start();
}
@Override
public void onGetGeoCodeResult(GeoCodeResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
// TODO Auto-generated method stub
if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
Toast.makeText(MapApiDemoActivity.this, "抱歉,未能找到结果", Toast.LENGTH_LONG)
.show();
return;
}
mBaiduMap.clear();
// mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
// .icon(BitmapDescriptorFactory
// .fromResource(R.drawable.icon_marka)));
mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
.getLocation()));
Toast.makeText(MapApiDemoActivity.this, result.getAddress(),
Toast.LENGTH_LONG).show();
String province = result.getAddressDetail().province;
String city = result.getAddressDetail().city;
if (province != null && city != null) {
}
}
}
android 日期选择器
package com.custom.dtselector.dialog;
import java.util.Calendar;
import com.custom.dtselector.NumericWheelAdapter;
import com.custom.dtselector.OnWheelChangedListener;
import com.custom.dtselector.WheelView;
import com.demo.dtselector.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DateSelectorDialog extends BaseDialog {
private static final int START_YEAR = 1900;
private static final int END_YEAR = 2100;
private int tdYear = 0;
private int tdMonth = 0;
private int tdDay = 0;
private WheelView wlvYear = null;
private WheelView wlvMonth = null;
private WheelView wlvDay = null;
private NumericWheelAdapter yearAdapter = null;
private NumericWheelAdapter monthAdapter = null;
private NumericWheelAdapter dayAdapter[] = new NumericWheelAdapter[4];
private NumericWheelAdapter curDayAdapter = null;
private int sltYear = 0;
private int sltMonth = 0;
private int sltDay = 0;
private String strSltYear = "";
private String strSltMonth = "";
private String strSltDay = "";
/**回调接口*/
private OnSelectDateEvent resultEvent = null;
@Override
public void init(Context context) {
// TODO Auto-generated method stub
this.context = context;
dialog = new Dialog(this.context, R.style.CustomDialog);
dialog.setContentView(R.layout.date_selector);
wlvYear = (WheelView)dialog.findViewById(R.id.date_selector_year);
wlvMonth = (WheelView)dialog.findViewById(R.id.date_selector_month);
wlvDay = (WheelView)dialog.findViewById(R.id.date_selector_day);
Button btnSelect = (Button)dialog.findViewById(R.id.btn_date_yes);
btnSelect.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
selectDate();
}
});
initCurDate();
initAdapters();
//对话框隐藏后,调用回调事件
dialog.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (resultEvent != null) {
resultEvent.onSelectDateResult(sltYear, sltMonth, sltDay);
}
}
});
}
@Override
public void update(Object obj) {
// TODO Auto-generated method stub
}
/**
* 设置回调事件
* @param event
*/
public void setOnSelectDateEvent(OnSelectDateEvent event) {
this.resultEvent = event;
}
private void initCurDate() {
Calendar instance = Calendar.getInstance();
tdYear = instance.get(Calendar.YEAR);
tdMonth = instance.get(Calendar.MONTH) + 1;
tdDay = instance.get(Calendar.DAY_OF_MONTH);
}
private int itemOfYear(int year) {
return year - START_YEAR;
}
private int itemOfMonth(int month) {
return month - 1;
}
private int itemOfDay(int day) {
return day - 1;
}
/**
* dapeter[0]->[1~28] dapeter[1]->[1~29] <br>
* dapeter[2]->[1~30] dapeter[3]->[1~31]
* @param year
* @param month
* @return
*/
private int indexAdapter(int year,int month) {
int index_data[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2) {
return DateTimeUtils.isLeapYear(year) ? 1 : 0;
} else {
if (index_data[month - 1] == 31) {
return 3;
} else {
return 2;
}
}
}
private void initAdapters() {
yearAdapter = new NumericWheelAdapter(START_YEAR,END_YEAR,"%4d");
monthAdapter = new NumericWheelAdapter(1,12,"d");
for (int i = 0; i < dayAdapter.length; i++) {
dayAdapter[i] = new NumericWheelAdapter(1,28 + i,"d");
}
sltYear = tdYear;
sltMonth = tdMonth;
sltDay = tdDay;
//赋值数据
wlvYear.setVisibleItems(3);
wlvYear.setCyclic(true);
wlvYear.setAdapter(yearAdapter);
int itemYear = itemOfYear(sltYear);
wlvYear.setCurrentItem(itemYear);
wlvMonth.setVisibleItems(3);
wlvMonth.setCyclic(true);
wlvMonth.setAdapter(monthAdapter);
int itemMonth = itemOfMonth(sltMonth);
wlvMonth.setCurrentItem(itemMonth);
int adapterIndex = indexAdapter(sltYear,sltMonth);
curDayAdapter = dayAdapter[adapterIndex];
wlvDay.setVisibleItems(3);
wlvDay.setCyclic(true);
wlvDay.setAdapter(curDayAdapter);
int itemDay = itemOfDay(sltDay);
wlvDay.setCurrentItem(itemDay);
wlvYear.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltYear = yearAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltYear));
if (strSltYear != null) {
sltYear = Integer.valueOf(strSltYear);
if (sltMonth == 2) {
int tmpIndex = indexAdapter(sltYear,sltMonth);
NumericWheelAdapter tmpAdapter = dayAdapter[tmpIndex];
if (tmpAdapter != curDayAdapter) {
curDayAdapter = tmpAdapter;
wlvDay.setAdapter(curDayAdapter);
}
}
} else {
sltYear = 0;
}
}
});
wlvMonth.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltMonth = monthAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltMonth));
if (strSltMonth != null) {
sltMonth = Integer.valueOf(strSltMonth);
if (sltYear != 0 && sltMonth != 0) {
int tmpIndex = indexAdapter(sltYear,sltMonth);
NumericWheelAdapter tmpAdapter = dayAdapter[tmpIndex];
if (tmpAdapter != curDayAdapter) {
curDayAdapter = tmpAdapter;
wlvDay.setAdapter(curDayAdapter);
}
}
} else {
sltMonth = 0;
}
}
});
wlvDay.addChangingListener(new OnWheelChangedListener() {
@Override
public void onChanged(WheelView wheel, int oldValue, int newValue) {
// TODO Auto-generated method stub
strSltDay = curDayAdapter.getItem(newValue);
android.util.Log.i("",String.format("old=%d new=%d v=%s",
oldValue,newValue,strSltDay));
if (strSltDay != null) {
sltDay = Integer.valueOf(strSltDay);
} else {
sltDay = 0;
}
}
});
}
private void selectDate() {
hide();
}
/**
* 回调接口
*/
public interface OnSelectDateEvent {
public void onSelectDateResult(int year,int month,int day);
};
}
支付宝 接口实例 js/android/ios
js 调用实现
android 调用实现
ios 调用实现
android xml文件操作
xml文件操作
public class XmlUtils {
/**
* 获取Document对象。根据xml文件的名字获取Document对象。
*
* @param file
* 要获取对象的xml文件全路径。
* @return 返回获取到的Document对象。
* @throws IOException
* 如果发生任何 IO 错误时抛出此异常。
* @throws SAXException
* 如果发生任何解析错误时抛出此异常。
* @throws ParserConfigurationException
* 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。
* @exception NullPointerException
* 如果file为空时,抛出此异常。
*/
public static Document parseForDoc(final String file) throws SAXException,
IOException, SecurityException, NullPointerException,
ParserConfigurationException {
return XmlUtils.parseForDoc(new FileInputStream(file));
}
/**
* 将一个xml字符串解析成Document对象。
*
* @param xmlStr
* 要被解析的xml字符串。
* @param encoding
* 字符串的编码。
* @return 返回解析后的Document对象。
* @throws IOException
* 如果发生任何 IO 错误时抛出此异常。
* @throws SAXException
* 如果发生任何解析错误时抛出此异常。
* @throws ParserConfigurationException
* 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。
*/
public static Document parseForDoc(String xmlStr, String encoding)
throws SAXException, IOException, ParserConfigurationException {
if (xmlStr == null) {
xmlStr = "";
}
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(
xmlStr.getBytes(encoding));
return XmlUtils.parseForDoc(byteInputStream);
}
/**
* 获取Document对象。根据字节输入流获取一个Document对象。
*
* @param is
* 获取对象的字节输入流。
* @return 返回获取到的Document对象。如果出现异常,返回null。
* @throws IOException
* 如果发生任何 IO 错误时抛出此异常。
* @throws SAXException
* 如果发生任何解析错误时抛出此异常。
* @throws ParserConfigurationException
* 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。
* @exception IllegalArgumentException
* 当 is 为 null 时抛出此异常。
*/
public static Document parseForDoc(final InputStream is)
throws SAXException, IOException, ParserConfigurationException,
IllegalArgumentException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(is);
} finally {
is.close();
}
}
/**
* 通过xpath表达式解析某个xml节点。
*
* @param obj
* 要被解析的xml节点对象。
* @param xPath
* xpath表达式。
* @param qName
* 被解析的目标类型。
* @return 返回解析后的对象。
* @throws XPathExpressionException
* 如果不能计算 expression。
*
* @exception RuntimeException
* 创建默认对象模型的 XPathFactory 遇到故障时。
* @exception NullPointerException
* 如果xPath为空时抛出时异常。
*/
private static Object parseByXpath(final Object obj, final String xPath,
QName qName) throws NullPointerException, RuntimeException,
XPathExpressionException {
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath path = xpathFactory.newXPath();
return path.evaluate(xPath, obj, qName);
}
/**
* 通过XPath表达式获取单个节点。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表达式。
* @return 返回获取到的节点。
*
* @throws XPathExpressionException
* 如果不能计算 expression。
*
* @exception RuntimeException
* 创建默认对象模型的 XPathFactory 遇到故障时。
* @exception NullPointerException
* 如果xPath为空时抛出时异常。
*/
public static Node parseForNode(final Object obj, final String xPath)
throws NullPointerException, RuntimeException,
XPathExpressionException
{
return (Node) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODE);
}
/**
* 通过XPath表达式获取某个xml节点的字符串值。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表达式。
* @return 返回获取到的节点的字符串值。
*
* @throws XPathExpressionException
* 如果不能计算 expression。
*
* @exception RuntimeException
* 创建默认对象模型的 XPathFactory 遇到故障时。
* @exception NullPointerException
* 如果xPath为空时抛出时异常。
*/
public static String parseForString(final Object obj, final String xPath)
throws NullPointerException, RuntimeException,
XPathExpressionException
{
return (String) XmlUtils
.parseByXpath(obj, xPath, XPathConstants.STRING);
}
/**
* 通过XPath表达式获取某个xml节点的布尔值。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表达式。
* @return 返回获取到的节点的布尔值。
*
* @throws XPathExpressionException
* 如果不能计算 expression。
*
* @exception RuntimeException
* 创建默认对象模型的 XPathFactory 遇到故障时。
* @exception NullPointerException
* 如果xPath为空时抛出时异常。
*/
public static Boolean parseForBoolean(final Object obj, final String xPath)
throws NullPointerException, RuntimeException,
XPathExpressionException
{
return (Boolean) XmlUtils.parseByXpath(obj, xPath,
XPathConstants.BOOLEAN);
}
/**
* 通过XPath表达式获取Node列表。
*
* @param obj
* 要被解析的對象。
* @param xPath
* XPath表达式。
* @return 返回获取到的Node列表。
*
* @throws XPathExpressionException
* 如果不能计算 expression。
*
* @exception RuntimeException
* 创建默认对象模型的 XPathFactory 遇到故障时。
* @exception NullPointerException
* 如果xPath为空时抛出时异常。
*/
public static List parseForNodeList(final Object obj, final String xPath)
throws NullPointerException, RuntimeException,
XPathExpressionException
{
List lists = new ArrayList();
NodeList nList = (NodeList) XmlUtils.parseByXpath(obj, xPath,
XPathConstants.NODESET);
if (nList != null) {
for (int i = 0; i < nList.getLength(); i++) {
lists.add(nList.item(i));
}
}
return lists;
}
/**
* 获取节点的制定属性。
*
* @param node
* 节点。
* @param attrName
* 属性名。
* @return 返回获取到的属性值。如果找不到相关的
*
*/
public static String getAttribute(final Object node, final String attrName) {
String result = "";
if ((node != null) && (node instanceof Node)) {
if (((Node) node).getNodeType() == Node.ELEMENT_NODE) {
result = ((Element) node).getAttribute(attrName);
} else {
// 遍历整个xml某节点指定的属性
NamedNodeMap attrs = ((Node) node).getAttributes();
if ((attrs.getLength() > 0) && (attrs != null)) {
Node attr = attrs.getNamedItem(attrName);
result = attr.getNodeValue();
}
}
}
return result;
}
/**
* 使用新节点替换原来的旧节点。
*
* @param oldNode
* 要被替换的旧节点。
* @param newNode
*
* 替换后的新节点。
* @exception DOMException
* 如果此节点为不允许
* newNode节点类型的子节点的类型;或者如果要放入的节点为此节点的一个祖先或此节点本身;或者如果此节点为
* Document 类型且替换操作的结果将第二个 DocumentType 或 Element 添加到
* Document 上。 WRONG_DOCUMENT_ERR: 如果 newChild
* 是从不同的文档创建的,不是从创建此节点的文档创建的,则引发此异常。
* NO_MODIFICATION_ALLOWED_ERR: 如果此节点或新节点的父节点为只读的,则引发此异常。
* NOT_FOUND_ERR: 如果 oldChild 不是此节点的子节点,则引发此异常。
* NOT_SUPPORTED_ERR: 如果此节点为 Document 类型,则如果 DOM 实现不支持替换
* DocumentType 子节点或 Element 子节点,则可能引发此异常。
*/
public static void replaceNode(Node oldNode, Node newNode) {
if ((oldNode != null) && (newNode != null)) {
oldNode.getParentNode().replaceChild(newNode, oldNode);
}
}
/**
* 将Document输出到指定的文件中。
*
* @param fileName
* 文件名。
* @param node
* 要保存的对象。
* @param encoding
* 保存的编码。
* @throws FileNotFoundException
* 指定的文件名不存在时,抛出此异常。
* @throws TransformerException
* 如果转换过程中发生不可恢复的错误时,抛出此异常。
*/
public static void saveXml(final String fileName, final Node node,
String encoding) throws FileNotFoundException, TransformerException {
XmlUtils.writeXml(new FileOutputStream(fileName), node, encoding);
}
/**
* 将Document输出成字符串的形式。
*
* @param node
* Node对象。
* @param encoding
* 字符串的编码。
* @return 返回输出成的字符串。
* @throws TransformerException
* 如果转换过程中发生不可恢复的错误时,抛出此异常。
* @throws UnsupportedEncodingException
* 指定的字符串编码不支持时,抛出此异常。
*/
public static String nodeToString(Node node, String encoding)
throws TransformerException, UnsupportedEncodingException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XmlUtils.writeXml(outputStream, node, encoding);
return outputStream.toString(encoding);
}
/**
* 将指定的Node写到指定的OutputStream流中。
*
* @param encoding
* 编码。
* @param os
* OutputStream流。
* @param node
* Node节点。
* @throws TransformerException
* 如果转换过程中发生不可恢复的错误时,抛出此异常。
*/
private static void writeXml(OutputStream os, Node node, String encoding)
throws TransformerException {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
DOMSource source = new DOMSource();
source.setNode(node);
StreamResult result = new StreamResult();
result.setOutputStream(os);
transformer.transform(source, result);
}
}
android地址选择器
1.省,市,区三级关联
2.地址数据本地化
3.自定义对话框
4.支付从xml文件,或对象文件加载
部分代码:
package com.demo.selector;
import java.io.InputStream;
import com.address.selector.City;
import com.address.selector.Country;
import com.address.selector.Province;
import com.address.selector.Region;
import com.demo.address.R;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class AddressSelectorDialog extends BaseDialog {
/**省类型*/
private static final int INDEX_PROVINCE = 1;
/**城市类型*/
private static final int INDEX_CITY = 2;
/**区县类型*/
private static final int INDEX_REGION = 3;
private static Country china = null;
private Spinner spnProvince = null;
private Spinner spnCity = null;
private Spinner spnRegion = null;
private ArrayAdapter dptProvince = null;
private ArrayAdapter dptCity = null;
private ArrayAdapter dptRegion = null;
private SpinnerSelectedListener proListener = new SpinnerSelectedListener();
private SpinnerSelectedListener cityListener = new SpinnerSelectedListener();
private SpinnerSelectedListener regionListener = new SpinnerSelectedListener();
//当前选择地区的索引值
private int provinceId = -1;
private int cityId = -1;
private int regionId = -1;
/**选择按钮*/
private Button btnSelect = null;
/**回调用事件*/
private OnSelectorCancel selectorCancel = null;
@Override
public void init(Context context) {
// TODO Auto-generated method stub
this.context = context;
dialog = new Dialog(this.context,R.style.CustomDialog);
dialog.setContentView(R.layout.adress_selector);
spnProvince = (Spinner)dialog.findViewById(R.id.spin_province);
spnProvince.setTag(new Integer(INDEX_PROVINCE));
spnCity = (Spinner)dialog.findViewById(R.id.spin_city);
spnCity.setTag(new Integer(INDEX_CITY));
spnRegion = (Spinner)dialog.findViewById(R.id.spin_region);
spnRegion.setTag(new Integer(INDEX_REGION));
btnSelect = (Button)dialog.findViewById(R.id.btn_select);
btnSelect.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
selectAddress();
}
});
//当对话框隐藏后调用[回调事件]
dialog.setOnCancelListener(new OnCancelListener(){
@Override
public void onCancel(DialogInterface arg0) {
// TODO Auto-generated method stub
if (selectorCancel != null) {
String proName = "";
String cityName = "";
String regName = "";
try {
Province tmpPro = china.provinceLst.get(provinceId);
proName = tmpPro.areaName;
City tmpCity = tmpPro.cityLst.get(cityId);
cityName = tmpCity.areaName;
Region tmpReg = tmpCity.regionLst.get(regionId);
regName = tmpReg.areaName;
} catch (Exception e) {
android.util.Log.e("selectorCancel???", e.getMessage());
}
selectorCancel.onSelectorResult(proName, cityName, regName);
}
}
});
//加载数据
if (china == null) {
loadCountryAddressData();
}
//加载完后,初始化适配器
initAdapters();
}
@Override
public void update(Object obj) {
// TODO Auto-generated method stub
}
private void loadCountryAddressData() {
try {
/**
* 反序化的包名,类名,版本ID必须一致,否则ClassNotFoundException
*/
InputStream stream = this.context.getAssets().open("china-city.obj");
china = Country.loadFromStream(stream);
//mHandler.sendEmptyMessage(0);
} catch (Exception e) {
android.util.Log.e("error", e.getMessage());
}
}
class SpinnerSelectedListener implements OnItemSelectedListener{
@Override
public void onItemSelected (AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//android.util.Log.i("", String.format("[pos=%d]",position));
int index = (Integer)parent.getTag();
//ArrayAdapter obj = (ArrayAdapter)(parent.getAdapter());
//String value = obj.getItem(position);
//android.util.Log.i("", "value=" + value);
if (index == INDEX_PROVINCE) {
provinceId = position;
if (isValideProvinceIndex(provinceId)) {
//改变城市选择
Province tmpProvince = china.provinceLst.get(provinceId);
String lstNames[] = tmpProvince.listNames();
if (lstNames == null) { //没有城市,当然没区县
provinceId = -1;
spnCity.setVisibility(View.INVISIBLE);
regionId = -1;
spnRegion.setVisibility(View.INVISIBLE);
return ;
} else {
if (spnCity.getVisibility() == View.INVISIBLE) {
spnCity.setVisibility(View.VISIBLE);
}
if (spnRegion.getVisibility() == View.INVISIBLE) {
spnRegion.setVisibility(View.INVISIBLE);
}
}
dptCity = new ArrayAdapter(context,
android.R.layout.simple_spinner_item,
lstNames);
dptCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCity.setAdapter(dptCity);
spnCity.setOnItemSelectedListener(cityListener);
}
} else if (index == INDEX_CITY) {
cityId = position;
if (isValideCityIndex(provinceId,cityId)) {
//改变区选择
Province tmpProvince = china.provinceLst.get(provinceId);
City tmpCity = tmpProvince.cityLst.get(cityId);
String lstNames[] = tmpCity.listNames();
if (lstNames == null) { //没有区县
regionId = -1;
spnRegion.setVisibility(View.INVISIBLE);
return ;
} else if (spnRegion.getVisibility() == View.INVISIBLE) {
spnRegion.setVisibility(View.VISIBLE);
}
dptRegion = new ArrayAdapter(context,
android.R.layout.simple_spinner_item,
lstNames);
dptRegion.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnRegion.setAdapter(dptRegion);
spnRegion.setOnItemSelectedListener(regionListener);
}
} else if (index == INDEX_REGION) {
regionId = position;
}
}
@Override
public void onNothingSelected(AdapterView parent) {
// TODO Auto-generated method stub
}
}
private void initAdapters() {
dptProvince = new ArrayAdapter(this.context,
android.R.layout.simple_spinner_item,
china.listNames());
//设置下拉列表的风格
dptProvince.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//设置适配器
spnProvince.setAdapter(dptProvince);
//设置侦听事件
spnProvince.setOnItemSelectedListener(proListener);
}
private boolean isValideProvinceIndex(int index) {
return (china != null) && (index >= 0 && index = 0) &&
(china.provinceLst.get(provinceIndex).cityLst.size() > cityIndex);
}
return false;
}
private void selectAddress() {
hide();
}
/**
* 调协回调事件
* @param selectorCancel
*/
public void setOnSelectorCancel(OnSelectorCancel selectorCancel) {
this.selectorCancel = selectorCancel;
}
/**
* 选择器关闭后,调用回调事件接口
*/
public interface OnSelectorCancel {
/**
* @param proName 省份名
* @param cityName 城市名
* @param regName 区县名
*/
public void onSelectorResult(String proName,String cityName,String regName);
};
}
C语言 棋子游戏 图形处理
(1)你可以选择两种玩法,与电脑,或对局
(2)游戏开始时,有两种选择但只能玩对局的,要不右边的棋子不能
被选中,(是电脑的棋子)
(3)想操纵左边棋子的朋友可以按 E,D,S,F键移动一个矩形光标.
光标包围自己的棋子时,可以按空格键,选中它,然后在一个没有
棋子的点按上空格键,即可移动棋子,小心!!!不要对方把您的棋
子吃掉了,如果您把对方的棋子都吃掉了,或者对方的棋子被您的棋
子包围了,使对方不能移动自己的棋子了,您就赢了这盘棋反之,
则输了这盘棋.
操纵右边棋子的朋友,可按 Up,Down,Left,Right键移动棋子,按Enter
键选中棋子.
(4)游戏规则:
1.您不能操纵对方的棋子
2.移动棋子时,起点到终点所成的直线中不能有其它任何棋子,否则
就不能移动棋子.
3.起点到终点形成的直线必须是棋盘上的某条直线,否则不能移动
棋子.
4.吃掉对方棋子的情况(满足如下关系)
A B A
B A B
则棋子B(第一种情况吃掉一个棋子,第二种情况吃掉两个棋子)被吃掉了
(5)可按Esc键退出游戏
Android计算器程序
支持多重小括号运算,
支持严格数学计算,
自适应分辨率