2013年8月29日星期四

Android Sqlite Example entry

 

through a simple example to learn Sqlite, student elective system, a demand that students can begin elective, elective has been completed can query to select the class.

 

designed first three tables, students, curriculum, course. Student table stores information about students, curriculum, curriculum information storage, table storage elective courses the student has chosen. Construction of the table can be SQLite Expert statement to test the software.

 

in Sqlite Expert to create a new database

 

 

switch to the SQL tab

 

 

to execute the following statement

 
  
create table if not exists Students(id integer primary key, name text not null) 
create table if not exists Subjects(id integer primary key, name text not null)
create table if not exists Subject_Select(id integer primary key unique, student_id integer references Students(id), subject_id integer references Subjects(id), unique_check text unique not null)
 
 

successfully created three tables, SQL statements without error

 

 

then use the code to create the database

 
  
public class TestSqlite { 

private static TestSqlite mInstance;

public static TestSqlite Instance() {
return TestSqlite.mInstance;
}

private final SQLiteDatabase mDatabase;

protected TestSqlite(Context context) {
TestSqlite.mInstance
= this;
mDatabase
= context.openOrCreateDatabase("select.db", Context.MODE_PRIVATE, null);
migrate();
}

private void migrate() {
final int version = mDatabase.getVersion();
final int currentVersion = 1;
if (version >= currentVersion) {
return;
}

mDatabase.beginTransaction();

switch (version) {
case 0:
createTables();
break;
}
mDatabase.setTransactionSuccessful();
mDatabase.setVersion(currentVersion);
mDatabase.endTransaction();

// 整理数据库
mDatabase.execSQL("VACUUM");
}

private void createTables() {
mDatabase.execSQL(
"create table if not exists Students(id integer primary key, name text not null)");
mDatabase.execSQL(
"create table if not exists Subjects(id integer primary key, name text not null)");
mDatabase.execSQL(
"create table if not exists Subject_Select(id integer primary key, "
+ "student_id integer references Students(id), " + "subject_id integer references Subjects(id),"
+ "unique_check text unique not null)");
}
}
 
 

due to the use of a single case, to rewrite the application:

 
  
public class TestApplication extends Application { 

@Override
public void onCreate() {
super.onCreate();
new TestSqlite(getApplicationContext());
}

}
 
 

in AndroidManifest.xml to add application

 
  
<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools
="http://schemas.android.com/tools"
package
="com.example.testsqlite"
android:versionCode
="1"
android:versionName
="1.0" >

<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion
="8"
tools:ignore
="OldTargetApi" />

<application
android:name="com.example.database.TestApplication"
android:allowBackup
="true"
android:icon
="@drawable/ic_launcher"
android:label
="@string/app_name"
android:theme
="@style/AppTheme" >
<activity
android:name="com.example.testsqlite.MainActivity"
android:label
="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
 
 

code structure:

 

 

run the program, it will create a database in a private directory

 

 

in TestSqlite add the code into the student and the subject

 
  
    private SQLiteStatement mInsertStudentInfoStatement; 

public long insertStudentInfo(long id, String name) {
if (name == null) {
return -1;
}

if (mInsertStudentInfoStatement == null) {
mInsertStudentInfoStatement
= mDatabase.compileStatement("insert or ignore into Students values (?,?)");
}
mInsertStudentInfoStatement.bindLong(
1, id);
mInsertStudentInfoStatement.bindString(
2, name);
return mInsertStudentInfoStatement.executeInsert();
}

private SQLiteStatement mInsertSubjectInfoStatement;

public long insertSubjectInfo(long id, String name) {
if (name == null) {
return -1;
}
if (mInsertSubjectInfoStatement == null) {
mInsertSubjectInfoStatement
= mDatabase.compileStatement("insert or ignore into Subjects values (?,?)");
}
mInsertSubjectInfoStatement.bindLong(
1, id);
mInsertSubjectInfoStatement.bindString(
2, name);
return mInsertSubjectInfoStatement.executeInsert();
}
 
 

these two operations do not use execSQL instead use SQLiteStatement, which can improve efficiency.

 

Insert Course code:

 
  
    private SQLiteStatement mInsertSubjectSelectStatement; 

public long insertSubjectSelectInfo(long student_id, long subject_id) {

if (mInsertSubjectSelectStatement == null) {
mInsertSubjectSelectStatement
= mDatabase
.compileStatement(
"insert or ignore into Subject_Select(student_id, subject_id, unique_check) values (?,?,?)");
}
String uniqueCheck
= student_id + "_" + subject_id;
mInsertSubjectSelectStatement.bindLong(
1, student_id);
mInsertSubjectSelectStatement.bindLong(
2, subject_id);
mInsertSubjectSelectStatement.bindString(
3, uniqueCheck);
return mInsertSubjectSelectStatement.executeInsert();
}
 
 

 

Subject_Select table's primary key id generated automatically, student_id and subject_id added references to constrain, and Subjects Students must be data in the table. unique_check added a unique constraint, the content makes up for the use of subject_id student_id and a string to prevent inserting duplicate data <​​p>  

be tested in MainActiviy

 
  
public class MainActivity extends Activity { 

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

TestSqlite.Instance().insertStudentInfo(
1, "小明");
TestSqlite.Instance().insertStudentInfo(
2, "小白");
TestSqlite.Instance().insertSubjectInfo(
1, "数学");
TestSqlite.Instance().insertSubjectInfo(
2, "语文");
TestSqlite.Instance().insertSubjectInfo(
3, "英语");
TestSqlite.Instance().insertSubjectInfo(
4, "物理");
TestSqlite.Instance().insertSubjectInfo(
5, "化学");
TestSqlite.Instance().insertSubjectSelectInfo(
1, 1);
TestSqlite.Instance().insertSubjectSelectInfo(
1, 3);
TestSqlite.Instance().insertSubjectSelectInfo(
1, 4);
TestSqlite.Instance().insertSubjectSelectInfo(
2, 2);
TestSqlite.Instance().insertSubjectSelectInfo(
2, 4);
TestSqlite.Instance().insertSubjectSelectInfo(
2, 5);
}
}
 
 

through the student's chosen course name query id:

 
  
    public List<String> getSelectSubjectNameByStudentId(long id) { 
List
<String> list = new ArrayList<String>();

String[] args
= new String[] { id + "" };
Cursor cursor
= mDatabase.rawQuery("select subjects.name from subjects,subject_select " +
"where subject_select.student_id = ? " +
"and subject_select.subject_id = subjects.id", args);
while (cursor.moveToNext()) {
list.add(cursor.getString(
0));
}

return list;
}
 
 

 Use the cursor in

One thing to note, in the splicing SQL statement, you can directly fight to the string parameter, for example:

 
  
Cursor cursor2 = mDatabase.rawQuery("select name from Students where id = " + id, null);
 
 

can

 
  
Cursor cursor2 = mDatabase.rawQuery("select name from Students where id = ?", new String[] { id + "" });
 
 

Under normal circumstances, these two effects is the same wording, but the second method has the advantage of not considering the escape character, like \% $ & / "This string can be used directly, while the first One way to consider escape, or can not properly be identified.

 

test query code:

 
  
        List<String> list = TestSqlite.Instance().getSelectSubjectNameByStudentId(1); 
for (String item : list) {
Log.i(getClass().getName(), item);
}
 
 

Thus, a simple database on the design is completed, and after further improvement, the software on the line, in the development of 2.0, when there has been a new demand, to have courses scores, which requires Subject_Select table to add a new field score. But also to keep the previous data, on the basis of 1.0 upgrade, but also add new features, which requires the database refactoring.

 

we have to do is

 

1) will Subject_Select rename Subject_Select_Obsolete

 

2) according to the new demand created a Subject_Select

 

3) will Subject_Select_Obsolete data copied to Subject_Select

 

4) Remove Subject_Select_Obsolete

 

SQL statement is

 
  
alter table Subject_Select rename to Subject_Select_Obsolete
 
 
  
create table Subject_Select(id integer primary key, student_id integer references Students(id), subject_id integer references Subjects(id),unique_check text unique not null, score real)
 
 
  
insert into Subject_Select (id,student_id,subject_id,unique_check) select id,student_id,subject_id,unique_check from Subject_Select_Obsolete
 
 
  
drop table Subject_Select_Obsolete
 
 

first to be judged in the code:

 
  
    private void migrate() { 
final int version = mDatabase.getVersion();
final int currentVersion = 2;
if (version >= currentVersion) {
return;
}

mDatabase.beginTransaction();

switch (version) {
case 0: {
createTables();
break;
}
case 1: {
updateTaples1();
break;
}
default:
break;
}
mDatabase.setTransactionSuccessful();
mDatabase.setVersion(currentVersion);
mDatabase.endTransaction();

// 整理数据库
mDatabase.execSQL("VACUUM");
}
 
 

In the above code, if the database version is 0, indicating that the database does not exist, create a table directly, if the database version is 1, indicating that the old version of the database, the database should be upgraded. Whether the upgrade or a new creation, version of the database are set to 2.

 

database upgrade code is:

 
  
    private void updateTaples1() { 
mDatabase.execSQL(
"alter table Subject_Select rename to Subject_Select_Obsolete");
mDatabase.execSQL(
"create table Subject_Select(id integer primary key, student_id integer references Students(id), subject_id integer references Subjects(id),unique_check text unique not null, score real)");
mDatabase.execSQL(
"insert into Subject_Select (id,student_id,subject_id,unique_check) select id,student_id,subject_id,unique_check from Subject_Select_Obsolete");
mDatabase.execSQL(
"drop table Subject_Select_Obsolete");
}
 
 

 

Python sequence (Sequence)

 

Sequence is a Python built-in types (built-in type), built-in type that is built on Python Interpreter inside type, three basic The Sequence Type is list (table), tuple (setting the table, or translated into tuple), range (range) . Can be seen as Python Interpreter defines such three class.

 

1, list, table

 

Python has a range of complex data types, is one of the most versatile list

 

class list ([iterable])

 

list with enclosed in square brackets and separated by commas , membership is not the same type can be, but is generally a type.

 

1.1 list object construction

 
  
>>> list = [] 
>>> list = [1,3]
>>> list
[
1, 3]
 
 You can also build this

 
  
>>> list()   # empty list 
[]
>>> [x for x in range(11)] # [x for x in iterable]
[0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list((3,5,6)) # list(iterable)
[
3, 5, 6]
 
 

 

1.2, change the list element value

 

list and is not the same string, string is immutable (immutable) type, list is Variable (mutable), on the list can be changed in whole or in part

 
  
>>> list = [list, 5] 
>>> list
[[
1, 3], 5]
>>> list[1] = 6
>>> list
[[
1, 3], 6]
 
 

list can be "slice" slice , to get a sub-list, it can "slice" assignment, change list

 

range reference syntax is [Lower: Upper: step], default step size is 1 , past few subscript from 0 start, from behind the subscript from -1 Start

 
  
>>> list = [1,2,3,4,5] 
>>> list[2:4]
[
3, 4]
>>> list[-3:]
[
3, 4, 5]
 
 The sections were assigned

change list

 
  
>>> list 
[
1, 2, 3, 4, 5]
>>> list[3:] = [5,4]
>>> list
[
1, 2, 3, 5, 4]
 
 

can one see from the above, change the list contents for operations such as assignment, do not print the results, which is the expression returns none. This is Python variable data structures (mutable Data Structure) design principles.

 

 

2, tuple

 

tuple is an immutable of (immutable)

 

class tuple ([iterable])

 

tuple construction

 
  
seq = ()  或  seq = tuple()   #构建empty tuple 
seq = (4,) 或 4, #构建只有一个元素的tuple (4),逗号是必不可少的,不然会返回数字4
seq = (3,4,5) 或 seq = 3,4,5
seq = tuple([3,4,5]) # 生成 (3,4,5)
 
 

iterable can be any support iteration of Sequence, Container. We use the parameters above list [3,4,5], also is to use tuple (3,4,5)

 

For tuple, it is important that the comma "," instead of parentheses, brackets from the above we can see that there is no ambiguity can be omitted, but some places have to be, for example,

 

f (a, b, c) indicates that the function takes three arguments

 

and f ((a, b, c)) indicates that the function accepts one parameter, which is a ternary tuple.

 

 

tuple can not be assigned, so the tuple used to do a different type ( heterogeneity ) set of sequences of elements, and list it used to do the same type ( homogeneity ) collection of elements.

 

 

3, range

 

range is also a type (type), which is a of digital serial (s sequence of numbers) , but immutable , and are often used in a for loop in

 

class range (stop)

 

class range (start, stop [, step])

 

For the first construction method, start the default value is 0, step defaults 1

 

When the step is positive, a range of element value r [i] = start + i * step and r [i] << / span> stop; step is negative, r [i] > stop

 
  
>>> range(6) 
[0, 1, 2, 3, 4, 5]
>>> tuple(range(0,-10,-2))
(0, -2, -4, -6, -8)
 
 

 

4. multiple assignment ( multiple assignment )

 

multiple assignment is such an assignment expression.

 
  
1 t = a,b,c 
2 a,b,c = t
 
 

and multiple assignment essence tuple packing and Sequence unpacking .

 

>>> t = a, b, c # which is tuple packing, constructed according to the syntax of a tuple, we know where t must be a tuple.

 

>>> a, b, c = t # This is Sequence unpacking, where t is the ternary Sequence long as can be, not necessarily the tuple, if t is not ternary, will throw a ValueError exception.

 

 

-----------------

 

Reference:

 

http://www.cnblogs.com/vamei/ archive/2012/05/28/2522677.html Vamei's blog

 

http:// docs.python.org/3/library/stdtypes.html # sequence-types-list-tuple-range Python documentation, built-in type Sequence

 

http://docs.python.org/ 3/tutorial/datastructures.html # tuples-and-sequences Python documentation, tutorial

javascript generate customized arcgis simpletoolbar

 

recent study ARCGIS for Javascript process, ESRI's online help saw such a Example , view the source code, I find that the left side of the tool is not very good scalability, and the elements of style can not be defined, so he began to design a custom border and Fill Color gadget.

 

1. Package setSymbol categories: the realization of such a prototype-based chain, has an initial (init), initialization (initOperater), generate style items (initItem), Add Item (addItem), edit the item (editItem, unrealized) , delete items (deleteItem) and so on. Detailed code is as follows:

 
        
   
  1 function ZSymbol(){ 
2 this.items=[{borderColor:"#ffcc00",fillColor:"#bfbfbf"},{borderColor:"#eaeaea",fillColor:"#dcdcdc"},{borderColor:"#efeaea",fillColor:"#dcacdc"}];
3 this.sym;
4 this.symItems;
5 this.symOperater;
6 }
7
8 ZSymbol.prototype={
9 initItem:function(){
10 for(var i=0;i<this.items.length;i++){
11 var item=this.addItem(this.items[i]);
12
13 this.symItems.appendChild(item);
14 }
15 },
16 initOperater:function(){
17 var add=document.createElement("INPUT");
18 add.type="button";
19 add.value="添加";
20 ZEvent.addListener(add,"click",function(){
21 var obj = zsymbol.addItem({borderColor:document.getElementById("borderColor").value,fillColor:document.getElementById("fillColor").value})
22 zsymbol.symItems.appendChild(obj);
23 });
24 this.symOperater.appendChild(add);
25
26 var edit=document.createElement("INPUT");
27 edit.type="button";
28 edit.value="编辑";
29 ZEvent.addListener(edit,"click",this.editItem);
30 this.symOperater.appendChild(edit);
31
32 var del=document.createElement("INPUT");
33 del.type="button";
34 del.value="删除";
35 ZEvent.addListener(del,"click",this.deleteItem);
36 this.symOperater.appendChild(del);
37
38 var operates=document.createElement("DIV");
39 operates.id="addContent";
40 operates.innerHTML='边框颜色<input type="text" onfocus="showPicker(this);" id="borderColor"><br/>填充颜色<input type="text" onfocus="showPicker(this)"; id="fillColor">';
41 this.symOperater.appendChild(operates);
42 },
43 selectItem: function(event){
44 drawPolygon(rgbToDojoColor(event.srcElement.style.borderColor),rgbToDojoColor(event.srcElement.style.backgroundColor));
45
46 },
47 addItem:function(obj){
48 var item=document.createElement("DIV");
49 item.className="symbolItem";
50 item.title="单击绘图,双击删除该样式"
51 item.style.borderColor=obj.borderColor;
52 item.style.backgroundColor=obj.fillColor;
53 ZEvent.addListener(item,"click",this.selectItem);
54 ZEvent.addListener(item,"mouseover",this._onmouseover);
55 ZEvent.addListener(item,"mouseout",this._onmouseout);
56 ZEvent.addListener(item,"dblclick",this.deleteItem);
57 // var itemEdit=document.createElement("SPAN");
58 // itemEdit.className="symbolEdit";
59 // itemEdit.title="编辑选中项";
60 // ZEvent.addListener(itemEdit,"click",this.editItem);
61 // item.appendChild(itemEdit);
62 //
63 // var itemDeletet=document.createElement("SPAN");
64 // itemDeletet.className="symbolDelete";
65 // itemDeletet.title="删除选中项";
66 // ZEvent.addListener(itemDeletet,"click",this.deleteItem);
67 // item.appendChild(itemDeletet);
68 return item;
69 },
70 editItem:function(){
71 alert(2);
72 },
73 deleteItem:function(evt){
74 if(confirm("确定删除此项吗?")){
75 zsymbol.symItems.removeChild(evt.srcElement);
76 }
77 },
78 _onmouseover:function(evt){
79 var obj=evt.srcElement.getElementsByTagName("SPAN");
80 for(var i=0;i<obj.length;i++){
81 obj[i].style.display="inline-block";
82 }
83 },
84 _onmouseout:function(evt){
85 var obj=evt.srcElement.getElementsByTagName("SPAN");
86 for(var i=0;i<obj.length;i++){
87 obj[i].style.display="none";
88 }
89 }
90
91 };
92
93 ZSymbol.prototype.init=function(){
94 var zSymbol=document.createElement("DIV");
95 zSymbol.className="symbolContainer";
96 this.sym=zSymbol;
97
98 var items=document.createElement("DIV");
99 items.className="symbolItems";
100 this.symItems=items;
101 zSymbol.appendChild(items);
102
103 var operaters=document.createElement("DIV");
104 operaters.className="symbolOperater";
105 this.symOperater=operaters;
106 zSymbol.appendChild(operaters);
107
108 document.body.appendChild(zSymbol);
109 this.initItem();
110 this.initOperater();
111 };
  
   View Code  
 

2. class mainly through ZEvent.addListener event registration method, purpose of doing so is to maintain setSymol object to reduce the coupling components other JS

 

can also be carried out using JQuery or Dojo event registration. Code is as follows:

 
        
   
 1 window.ZEvent = { //自定义事件处理 
2 addListener: function(obj, target, act){
3 if (obj.attachEvent)
4 obj.attachEvent("on" + target, act);
5 if (obj.addEventListener)
6 obj.addEventListener(target, act, false);
7 },
8 removeListener: function(obj, target, act){
9 if (obj.detachEvent)
10 obj.detachEvent("on" + target, act);
11 if (obj.removeEventListener)
12 obj.removeEventListener(target, act, false);
13 }
14 }
  
   View Code  
 

3.setSymbol supports manual input color value and generate elements of style, of course, in order to obtain a better user experience, the example uses the dojo color picker for color acquisition.

 

Because IE10, Chrome obtained colored value is in decimal, IE8 get is hexadecimal, which requires a color conversion function to get Arcgis supported color format.

 

code is as follows:

 
        
   
 1 function rgbToDojoColor(obj){ 
2 var result;
3 var temp=new Array();
4 if(obj.lastIndexOf("rgb")>=0){
5 result=obj.replace("rgb(","");
6 result=result.replace(")","");
7 temp=result.split(',');
8 }
9 else if(obj.lastIndexOf("#")>=0){
10
11
12 result=obj.replace("#","");
13 temp.push(parseInt("0x"+result.substring(0,2)));
14 temp.push(parseInt("0x"+result.substring(2,4)));
15 temp.push(parseInt("0x"+result.substring(4,6)));
16 }
17 return temp;
18 }
  
   View Code  
 

4. At this point, the tool's main code has been completed. Operating results are shown below:

 

 

5. release Note: This example source files at the end of the article, published modify the two addresses.

 

indexMap3.5.html in Arcgis Api address:

 

 

init.js the map service address:

 

 

Summary: The preparation gadget has several deficiencies:

 

1. deleteItem method in place, call the declared variables zsymbol, is not conducive to the code porting and redefine

 

2.Item of _onmouseover and _onmouseout method has problems, so the style of editing and deleting the small icon failed to achieve.

 

3. For the text of the deficiencies, please feel free to correct me park friends! Meanwhile, in this beautiful "Tanabata" day, I wish the program ape / Yuan were happy Tanabata! ! !

 

PropertyGrid attributes VS imitation event window

 

renderings : .

 

First we went to rewrite PropertyGrid:

 
  
internal class MyPropertyGrid : System.Windows.Forms.PropertyGrid 
{
private System.ComponentModel.Container components = null;

public MyPropertyGrid()
{
InitializeComponent();
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}

#region Component Designer generated code
private void InitializeComponent()
{
components
= new System.ComponentModel.Container();
}
#_endregion

public void ShowEvents(bool show)
{
ShowEventsButton(show);
}
}
 
 

rewrite Container used to package components :

 
  
class IDEContainer : Container 
{
class IDESite : ISite
{
private string name = "";
private IComponent component;
private IDEContainer container;

public IDESite(IComponent sitedComponent, IDEContainer site, string aName)
{
component
= sitedComponent;
container
= site;
name
= aName;
}

public IComponent Component
{
get { return component; }
}
public IContainer Container
{
get { return container; }
}

public bool DesignMode
{
get { return false; }
}

public string Name
{
get { return name; }
set { name = value; }
}

public object GetService(Type serviceType)
{
return container.GetService(serviceType);
}
}

public IDEContainer(IServiceProvider sp)
{
serviceProvider
= sp;
}

protected override object GetService(Type serviceType)
{
object service = base.GetService(serviceType);
if (service == null)
{
service
= serviceProvider.GetService(serviceType);
}
return service;
}

public ISite CreateSite(IComponent component)
{
return CreateSite(component, "UNKNOWN_SITE");
}

protected override ISite CreateSite(IComponent component, string name)
{
ISite site
= base.CreateSite(component, name);
if (site == null)
{
}
return new IDESite(component, this, name);
}

private IServiceProvider serviceProvider;
}
 
 

to achieve EventBindingService interface used for event processing :

 
  
public class EventBindingService : System.ComponentModel.Design.EventBindingService 
{
public EventBindingService(IServiceProvider myhost)
:
base(myhost)
{
}

#region IEventBindingService Members
protected override string CreateUniqueMethodName(IComponent component, EventDescriptor e)
{
throw new Exception("The method or operation is not implemented.");
}

protected override System.Collections.ICollection GetCompatibleMethods(System.ComponentModel.EventDescriptor e)
{
List
<object> l = new List<object>();
return l;
}

protected override bool ShowCode(System.ComponentModel.IComponent component, System.ComponentModel.EventDescriptor e, string methodName)
{
throw new Exception("The method or operation is not implemented.");
}

protected override bool ShowCode(int lineNumber)
{
throw new Exception("The method or operation is not implemented.");
}

protected override bool ShowCode()
{
throw new Exception("The method or operation is not implemented.");
}
#_endregion
}
 
 
主窗体页面代码(在这里去绑定控件):
 
  
private System.ComponentModel.IContainer components = null; 
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#_endregion

PropertiesForm propertiesForm;
DesignSurface designSurface;

public MainForm()
{
designSurface
= new DesignSurface();

propertiesForm
= new PropertiesForm(designSurface);
propertiesForm.Show();

IServiceContainer serviceContainer
= (IServiceContainer)designSurface.GetService(typeof(IServiceContainer));
serviceContainer.AddService(
typeof(IEventBindingService), new EventBindingService(designSurface));

ISelectionService selectionService
= (ISelectionService)designSurface.GetService(typeof(ISelectionService));
selectionService.SelectionChanged
+= new EventHandler(OnSelectionChanged);

designSurface.BeginLoad(
typeof(Form));

}

private void OnSelectionChanged(object sender, System.EventArgs e)
{
ISelectionService s
= (ISelectionService)designSurface.GetService(typeof(ISelectionService));
IDesignerHost designerHost
= (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));

object[] selection;
if (s.SelectionCount == 0)
propertiesForm.SetObjectToPropertyGrid(
null);
else
{
selection
= new object[s.SelectionCount];
s.GetSelectedComponents().CopyTo(selection,
0);
propertiesForm.SetObjectToPropertyGrid(selection);
}
}
 
 

PropertyGrid page code ( mainly PropertyGrid bound data and add the Events tab ):

 
  
private DesignSurface designSurface; 
private System.ComponentModel.IContainer components = null;
private MyPropertyGrid pg = null;

protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

public PropertiesForm(DesignSurface designSurface)
{
this.designSurface = designSurface;

this.SuspendLayout();

pg
= new MyPropertyGrid();
pg.Parent
= this;
pg.Dock
= DockStyle.Fill;
this.ResumeLayout(false);
}

internal void SetObjectToPropertyGrid(object[] c)
{
IDesignerHost designerHost
= (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
if (c == null)
pg.SelectedObject
= null;
else
pg.SelectedObjects
= c;

if (designerHost != null)
{
pg.Site
= (new IDEContainer(designerHost)).CreateSite(pg);
pg.PropertyTabs.AddTabType(
typeof(System.Windows.Forms.Design.EventsTab), PropertyTabScope.Document);
pg.ShowEvents(
true);
}
else
{
pg.Site
= null;
}
}
 
 

want the source code , please add base.

 

WPF, AE technical exchange group : 94234450

 

group link : http://wp.qq.com/wpa/ qunwpa? idkey = 14e3d476b4a53a3a1502183e5a384d94b8be74b7510c0a76e67c4dec61f23781

 
 

Android

 

Introduction

 

dialog is also essential for the application of a component in Android is no exception, a dialog box prompts for some important information that require additional user interaction or some of the content helpful. This blog will explain the use of the dialog box under Android, In this blog, you will learn some general properties dialog settings dialog boxes and all kinds of use, and will provide small to show all effects Demo .

 

Dialog

 

Dialog , dialog, a dialog box is a small window, and will not fill over the entire screen display mode usually requires the user to take action in order to proceed to the rest of the operation.

 

Android provides a rich dialog support, which provides the following four commonly used dialog:

 
      
  • AlertDialog: Warning dialog box, the most widely used one of the most feature rich dialog.
  •   
  • ProgressDialog: progress bar dialog box, except for the progress bar for a simple package.
  •   
  • DatePickerDialog: Date dialog box.
  •   
  • TimePickerDialog: Time dialog box.
  •  
 

all dialogs are directly or indirectly inherit from the Dialog class, while AlterDialog inherit directly from Dialog, several other classes are inherited from AlterDialog.

 

 

AlertDialog

 

AlertDialog inherited from the Dialog class, built for the Android AlterDialog, it can contain a title , a message or a select list content up to three buttons. Created AlterDialog recommend using one of its internal class AlterDialog.Builder created. Using Builder object, you can set AlterDialog various properties, and finally through Builder.create () you can get AlterDialog object, if only need to show this AlterDialog, can generally be used directly Builder.show () method, which returns an object AlterDialog , and displays it.

 

if only need to prompt a message to the user, it can be used directly to set some properties AlterDialog message that relates to methods are:

 
      
  • AlterDialog create (): according to the set of attributes, creating a AlterDialog.
  •   
  • AlterDialog show (): according to the set of attributes, creating a AlterDialog, and displayed on the screen.
  •   
  • AlterDialog.Builder setTitle (): set the title.
  •   
  • AlterDialog.Builder setIcon (): set the title of the icon.
  •   
  • AlterDialog.Builder setMessage (): set the title of the content.
  •   
  • AlterDialog.Builder setCancelable (): Set whether modal, generally set to false, modal, the user must take action in order to continue with the rest of the operation.
  •  
 

Tips: AlterDialog.Builder many ways to set properties returned are the AlterDialog.Builder object, so you can write code using the chain, which is more convenient.

 

When a dialog box called show () method, the display on the screen, if you need to remove it, you can use DialogInterface interface declares two methods, cancel () and dismiss () to take or remove the dialog box, which The role of the two methods is the same, but the recommended dismiss (). Dialog and AlterDialog have achieved DialogInterface interface, so long as the dialog, can use these methods to eliminate the dialog box.

 

following a simple Demo, take a look at how the message AlterDialog of:

 

Example:

 
  
      
  
 1         btnGeneral.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // TODO Auto-generated method stub
6 AlertDialog.Builder builder = new AlertDialog.Builder(
7 MainActivity.this);
8 builder.setTitle("提示");
9 builder.setMessage("这是一个普通的对话框!");
10 builder.setIcon(R.drawable.ic_launcher);
11 builder.setCancelable(false);
12 builder.setPositiveButton("知道了!", new OnClickListener() {
13 @Override
14 public void onClick(DialogInterface dialog, int which) {
15 dialog.cancel();
16 }
17 });
18 builder.create().show();
19 }
20 });
  
      
 
 

showing the effect of:

 

 

 

AlterDialog button

 

AlterDialog built three buttons can be used directly setXxxButton () method to set, for the average dialog box with three buttons are basically good enough, the following is the signature of these three methods:

 
      
  • AlterDialog.Builder setPositiveButton (CharSquence text, DialogInterFace.OnClickListener): an active button, generally used for "OK" or "continue," and other operations.
  •   
  • AlterDialog.Builder setNegativeButton (CharSquence text, DialogInterFace.OnClickListener): a negative buttons are generally used for the "Cancel" operation.
  •   
  • AlterDialog.Builder setNeutralButton (CharSquence text, DialogInterFace.OnClickListener): a more neutral button, generally used for "ignore", "Remind Me Later" and other operations.
  •  
 

described above DialogInterface interface also provides a range of incident response, these three buttons are required to pass a DialogInterFace.OnClickListener interface object, to achieve its click event trigger, need to implement this interface in an onClick (DialogInterface dialog , int which), dialog box for the current trigger event object interface, can be directly cast to AlterDialog operate; which button to click on the identifier is an integer data, for these three buttons, each button using a different data type int identified: Positive (-1), Negative (-2), Neutral (-3).

 

In addition to dedicated button clicks achieved DialogInterFace.OnClickListener incidents, DialogInterface also provides some other events for the Dialog object response to these events just Dialog statement cycle response of each state, one can understand, on the not explained in detail, the following is a description of these events:

 
      
  • interface DialogInterface.OnCancelListener: When the dialog box call cancel () method when triggered.
  •   
  • interface DialogInterface.OnDismissListener: When the dialog box calls dismiss () method when triggered.
  •   
  • interface DialogInterface.OnShowListener: When the dialog box call show () method when triggered.
  •   
  • interface DialogInterface.OnMultiChoiceListener: When using the multiple-selection list box, and select when triggered.
  •  
 

Example:

 
  
      
  
 1         btnButtons.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // TODO Auto-generated method stub
6 AlertDialog.Builder builder = new AlertDialog.Builder(
7 MainActivity.this);
8 builder.setTitle("提示");
9 builder.setMessage("这是一个多按钮普通的对话框!");
10 builder.setIcon(R.drawable.ic_launcher);
11 builder.setPositiveButton("确定", new OnClickListener() {
12
13 @Override
14 public void onClick(DialogInterface dialog, int which) {
15 Toast.makeText(MainActivity.this, "确定被点击",
16 Toast.LENGTH_SHORT).show();
17 dialog.dismiss();
18 }
19 });
20 builder.setNegativeButton("否定", new OnClickListener() {
21
22 @Override
23 public void onClick(DialogInterface dialog, int which) {
24 // TODO Auto-generated method stub
25 Toast.makeText(MainActivity.this, "否定被点击",
26 Toast.LENGTH_SHORT).show();
27 dialog.dismiss();
28 }
29 });
30 builder.setNeutralButton("忽略", new OnClickListener() {
31
32 @Override
33 public void onClick(DialogInterface dialog, int which) {
34 // TODO Auto-generated method stub
35 Toast.makeText(MainActivity.this, "忽略被点击",
36 Toast.LENGTH_SHORT).show();
37 dialog.cancel();
38 }
39 });
40 builder.show();
41 }
42 });
  
      
 
 

showing the effect of:

 

 

 

AlterDialog list form

 

AlterDialog In addition to showcasing some of the tips, you can also demonstrate a form of a list, you need to Builder.setItems (CharSequence [] items, DialogInterface.OnClickListener listener) method to set, it needs to pass an array of type CharSequenece to Data binding list, it also need to pass a DialogInterface.OnClickListener interface in response to clicking the list item, and this interface onClick method which parameters click the trigger for the current item items in subscript.

 

Example:

 
  
      
  
 1         btnListView.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // TODO Auto-generated method stub
6 AlertDialog.Builder builder = new AlertDialog.Builder(
7 MainActivity.this);
8 builder.setTitle("请选择城市");
9 //items使用全局的finalCharSequenece数组声明
10 builder.setItems(items, new OnClickListener() {
11 @Override
12 public void onClick(DialogInterface dialog, int which) {
13 // TODO Auto-generated method stub
14 String select_item = items[which].toString();
15 Toast.makeText(MainActivity.this,
16 "选择了---》" + select_item, Toast.LENGTH_SHORT)
17 .show();
18 }
19 });
20 builder.show();
21 }
22 });
  
      
 
 

results show:

 

 

AlterDialog radio list

 

AlterDialog radio is also possible to use a list style, using Builder.setSingleChoiceItems (CharSequenece [] items, int checkedItem, DialogInterface.OnClickListener listener), this method has several overloads, mainly in response to different data sources , items for the list item array, checkedItem initial option, listener response to a click event. Sometimes does not necessarily need to close the dialog box after selected, you can set two buttons, used to determine the selection.

 

Example:

 
  
      
  
 1         btnListViewSingle.setOnClickListener(new View.OnClickListener() { 
2 @Override
3 public void onClick(View v) {
4 // TODO Auto-generated method stub
5 AlertDialog.Builder builder = new AlertDialog.Builder(
6 MainActivity.this);
7 builder.setTitle("请选择一下城市");
8 builder.setSingleChoiceItems(items, 1, new OnClickListener() {
9
10 @Override
11 public void onClick(DialogInterface dialog, int which) {
12 // TODO Auto-generated method stub
13 String select_item = items[which].toString();
14 Toast.makeText(MainActivity.this,
15 "选择了--->>" + select_item, Toast.LENGTH_SHORT)
16 .show();
17 }
18 });
19 builder.setPositiveButton("确定", new OnClickListener() {
20 @Override
21 public void onClick(DialogInterface dialog, int which) {
22 dialog.dismiss();
23 }
24 });
25 builder.show();
26 }
27 });
  
      
 
 

results show:

 

 

 

AlterDialog multiple-selection list

 

AlterDialog In addition to single-selection list, as well as multiple-choice list. You can use Builder.setMultiChoiceItems (CharSequence [] items, boolean [] checkedItems, DialogInterface.OnMultiChoiceClickListener listener), this method also has a variety of overloads for this method, items in an array as the data source; checkedItems is the default option, because is a multi-selection list, so if you need to set all settings, if not checked by default, returns Null; listener for multiple options Click triggering event.

 

Example:

 
  
      
  
 1         btnListViewMulti.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // TODO Auto-generated method stub
6 AlertDialog.Builder builder = new AlertDialog.Builder(
7 MainActivity.this);
8 builder.setTitle("请选择城市");
9 builder.setMultiChoiceItems(items, new boolean[] { true, false,
10 true }, new OnMultiChoiceClickListener() {
11 @Override
12 public void onClick(DialogInterface dialog, int which,
13 boolean isChecked) {
14 // TODO Auto-generated method stub
15 String select_item = items[which].toString();
16 Toast.makeText(MainActivity.this,
17 "选择了--->>" + select_item, Toast.LENGTH_SHORT)
18 .show();
19 }
20 });
21 builder.setPositiveButton("确定", new OnClickListener() {
22 @Override
23 public void onClick(DialogInterface dialog, int which) {
24 dialog.dismiss();
25 }
26 });
27 builder.show();
28 }
29 });
  
      
 
 

results show:

 

 

 

AlertDialog custom style

 

Sometimes, Android comes with some style settings have been unable to meet demand, then you can use custom styles, custom an XML layout file, with the contents of this document as the style of AlertDialog display on the screen, so you can a flexible customization dialog. For custom XML file, you can use LayoutInflater.from (Context). Inflate (int, ViewGroup) way its dynamic loading, and then use Builder.setView (View) to view the loaded object associated with the Builder, the last regular show () can be.

 

layout code:

 
  
      
  
 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical"
6 android:paddingBottom="@dimen/activity_vertical_margin"
7 android:paddingLeft="@dimen/activity_horizontal_margin"
8 android:paddingRight="@dimen/activity_horizontal_margin"
9 android:paddingTop="@dimen/activity_vertical_margin"
10 tools:context=".MainActivity" >
11
12 <Button
13 android:id="@+id/btnGeneral"
14 android:layout_width="wrap_content"
15 android:layout_height="wrap_content"
16 android:text="普通对话框" />
17
18 <Button
19 android:id="@+id/btnButtons"
20 android:layout_width="wrap_content"
21 android:layout_height="wrap_content"
22 android:text="多按钮的普通对话框" />
23
24 <Button
25 android:id="@+id/btnListView"
26 android:layout_width="wrap_content"
27 android:layout_height="wrap_content"
28 android:text="列表选择对话框" />
29
30 <Button
31 android:id="@+id/btnListViewSingle"
32 android:layout_width="wrap_content"
33 android:layout_height="wrap_content"
34 android:text="单选列表选择对话框" />
35
36 <Button
37 android:id="@+id/btnListViewMulti"
38 android:layout_width="wrap_content"
39 android:layout_height="wrap_content"
40 android:text="多选列表选择对话框" />
41
42 <Button
43 android:id="@+id/btnProgressDialog"
44 android:layout_width="wrap_content"
45 android:layout_height="wrap_content"
46 android:text="滚动等待对话框" />
47
48 <Button
49 android:id="@+id/btnProgressDialogH"
50 android:layout_width="wrap_content"
51 android:layout_height="wrap_content"
52 android:text="进度条对话框" />
53 <Button
54 android:id="@+id/btnCustomDialog"
55 android:layout_width="wrap_content"
56 android:layout_height="wrap_content"
57 android:text="自定义对话框" />
58 </LinearLayout>
  
      
 
 

implementation code:

 
  
      
  
 1         btnCustomDialog.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
6 View view=LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_signin,null);
7 Button btn=(Button)view.findViewById(R.id.btnCustom);
8 btn.setOnClickListener(new View.OnClickListener() {
9
10 @Override
11 public void onClick(View v) {
12 // TODO Auto-generated method stub
13 alertDialog.dismiss();
14 Toast.makeText(MainActivity.this, "表单填写完成",
15 Toast.LENGTH_SHORT).show();
16 }
17 });
18 builder.setView(view);
19 alertDialog=builder.show();
20 }
21 });
  
      
 
 

results show:

 

 

 

ProgressDialog

 

Sometimes, just need to prompt the user to wait, for example, in the implementation of the time-consuming operation, etc., can be used to display a progress dialog progress information that prompts the user to wait, this time you can use ProgressDialog. ProgressDialog is used most of them can see ProgressBar, is actually a package of the ProgressBar dialog.

 

ProgressDialog There are two display methods, one is a rolling ring icon , you can display a title and some text content to wait for the dialog box; another one is with a progress bar scale, and general usage of the progress bar. Both styles through ProgressDialog.setProgressStyle (int style) settings, you can set ProgressDialog two constants: STYLE_HORIZONTAL: Scale rolling; STYLE_SPINNER: icon scrolling, the default option.

 

For scrolling icons can be used in two ways, one is the conventional call the constructor, and then set the corresponding property; Another is the direct use ProgressDialog static method show (), returns a ProgressDialog object directly, and call the show () method.

 

Example:

 
  
      
  
 1         btnProgressDialog.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // 第一种方法,使用ProgressDialog构造函数
6 progressDialog = new ProgressDialog(MainActivity.this);
7 progressDialog.setIcon(R.drawable.ic_launcher);
8 progressDialog.setTitle("等待");
9 progressDialog.setMessage("正在加载....");
10 progressDialog.show();
11 //第二种方法,使用静态的show方法
12 //progressDialog=ProgressDialog.show(MainActivity.this, "等待", "正在加载....", false, false);
13 new Thread(new Runnable() {
14
15 @Override
16 public void run() {
17 try {
18 Thread.sleep(5000);
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 finally{
23 progressDialog.dismiss();
24 }
25 }
26 }).start();
27 }
28 });
  
      
 
 

results show:

 

 

For a graduated ProgressDialog, apart from the AlertDialog in inherited property, there are some necessary attributes need to be set, the following method has the getter method:

 
      
  • setMax (int max): maximum scale.
  •   
  • setProgress (int value): First progress.
  •   
  • setSecondaryProgress (int value): Second progress.
  •  
 

Example:

 
  
      
  
 1         btnProgressDialog.setOnClickListener(new View.OnClickListener() { 
2
3 @Override
4 public void onClick(View v) {
5 // 第一种方法,使用ProgressDialog构造函数
6 progressDialog = new ProgressDialog(MainActivity.this);
7 progressDialog.setIcon(R.drawable.ic_launcher);
8 progressDialog.setTitle("等待");
9 progressDialog.setMessage("正在加载....");
10 progressDialog.show();
11 //第二种方法,使用静态的show方法
12 //progressDialog=ProgressDialog.show(MainActivity.this, "等待", "正在加载....", false, false);
13 new Thread(new Runnable() {
14
15 @Override
16 public void run() {
17 try {
18 Thread.sleep(5000);
19 } catch (Exception e) {
20 e.printStackTrace();
21 }
22 finally{
23 progressDialog.dismiss();
24 }
25 }
26 }).start();
27 }
28 });
  
      
 
 

results show:

 

 

source download

 

Summary

 

above describes the common dialog boxes on the content, DatePickerDialog and TimePickerDialog In addition there is an introduction to the blog, you can see: Android - UI's DatePicker, TimePicker ... . The latest official document from the learned, it is recommended to use FragmentDialog to operate Dialog, so easy to manage content on Fragment, no introduction, later introduced Fragment say that after using FragmentDialog how to create a dialog. In the source code there is a FragmentDialog simple example, are interested can download them to see.

 

Please support the original, respect for the original, reproduced please indicate the source. Thank you.