Monday, November 29, 2010

Javascript to Numeric or to TimeString simple

__ToNumeric=function(s){
        var i=0;
        do{
            var c = s.charAt(i);
            if(c=='0')i++;else break;
        }while(i<s.length);
        if(i==s.length)return 0;
        return parseInt(i==0?s:s.substr(i,s.length-i));
    }

    __ToTimeStr=function(n){
        var v=n+'';
        return (v.length==1?'0'+v:v);
    }

Javascript super object for (data entity and more )

Энэ объектыг бичиж орууллаа. Учир нь элдэв өгөгдөлийг client талд утга хадгалах javascript object шаардлагатай болдог дутагдлыг төгс нөхнө. Ашиглаад үзээрэй.
Чадвар нь: JSON, JQuery, Array, Attr авч болон өгөх


var _objects = {
    interface0 : {
        data : new Array(),
        getString : function() { return JSON.stringify(this); },
        extend : function(args) {
            var obj = (typeof args == 'string') ? eval('(' + args + ')') : args;
            $.extend(this, obj, true);
            return this;
        },
        parse : function(args) {
            var i = args.toString().indexOf('{');
            if (i == -1) i = args.toString().indexOf('}');
            if (i == -1) { return { data : args.toString() }; }
            return (typeof args == 'string') ? eval('(' + args + ')') : args;
        }
    },
    create : function(){
        var o = { };
        if (arguments.length == 1) {
            try {
                //Long l = Long.parseLong(arguments[0]);
                o = $.extend({}, { id : arguments[0] }, true);
            } catch (ex) {
                o = $.extend({}, { id : 0 }, true);
                var obj = (typeof arguments[0]=='string')?eval('('+arguments[0]+')'):arguments[0];
                o = $.extend({}, obj, true);
            }
        } else if (arguments.length == 2) {
            var obj = (typeof arguments[1]=='string')?eval('('+arguments[1]+')'):arguments[1];
            o = $.extend({}, obj, true);
            o = $.extend(o, { id : arguments[0] }, true);
        } else
            o = $.extend({}, { id : 0 }, true);
        o = $.extend(o, this.interface0, true);
        o.data = new Array();
        //usage::
        //var n = new MyEntity(10);
        //n.hi = "hi boroo";
        //n.extend({name:"boroo"});
        //var obj = new MyEntity(20, n.getString());
        //var n = new MyEntity(10, "{name:'baatar'}");
        //n.data["a"]="b";
        //alert( n.data["a"] );
        return o;
    }
//var a = _objects.create(22);
//var b = _objects.create(33);
//b.hi = "welcome, boroo";
//b.id="1";
//a.extend(b.getString());
//alert(a.data.length);
};

JQuery UI datepicker mn mongolia localization

jquery.ui.datepicker-mn.js файлыг ~/scripts/jquery/i18n/ мэт санд байршуулаад

jQuery(function($){
    $.datepicker.regional['mn'] = {
        closeText: 'Хаах',
        prevText: 'Өмнөх',
        nextText: 'Дараах',
        currentText: 'Өнөөдөр',
        monthNames: ['1-р сар','2-р сар','3-р сар','4-р сар','5-р сар','6-р сар',
        '7-р сар','8-р сар','9-р сар','10-р сар','11-р сар','12-р сар'],
        monthNamesShort: ['1 сар', '2 сар', '3 сар', '4 сар', '5 сар', '6 сар',
        '7 сар', '8 сар', '9 сар', '10 сар', '11 сар', '12 сар'],
        dayNames: ['Ням', 'Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'],
        dayNamesShort: ['Ням', 'Дав', 'Мяг', 'Лха', 'Пүр', 'Баа', 'Бям'],
        dayNamesMin: ['Ня','Да','Мя','Лх','Пү','Ба','Бя'],
        weekHeader: '7 хоног',
        dateFormat: 'yy.mm.dd',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['mn']);
});

usage

$.datepicker.setDefaults($.datepicker.regional['mn']);
код нь өөрөө хэлний сонголтыг хийж бэлэн болгоно.

simple

<div class="right" style="width:300px;">
                <span class="right-line-items">                   
                    <a href="#" id="date-toggler">Он сар өдөр сонгох</a>
                    <script type="text/javascript">
                        $(function() {
                            $("#date-toggler").click(function(){
                                $("#date-selector").datepicker({
                                    buttonImageOnly: true,
                                    showOtherMonths: true,
                                    selectOtherMonths: true,
                                    showAnim: "slideDown",
                                    changeMonth: true,
                                    changeYear: true,
                                    onSelect:function(){
                                        var dateString = $(this).val();
                                        $(this).datepicker('destroy');
                                        _view(dateString);
                                    },
                                    dateFormat: DEFAULT_DATE_FORMAT//yy.mm.dd
                                });
                                $("#date-selector").css("font-size", "65%")
                                        .css("right", "90px").css("margin-top","26px");
                            });
                        });
                    </script>
                </span>
                <div id="date-selector" style="position:absolute;z-index:1000;"></div>
            </div>

JQuery insensitive :contains ( find, filter ) how to make as :containsi simple

Энэ код нь том жижиг үсэг ялгахгүй хайлт хийх боломжийг олгох өргөтгөсөн функц юм.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.4.4.js"></script>
</head>
<body>
 
<div>boroo boldbaatar</div>

<div>Harin ene bol minii naiz</div>
<div>Bi bol boroo</div>
<div>B.oroo</div>
     
   
<script>
$.extend($.expr[':'], {
            'containsi': function(elem, i, match, array) {
                //(elem.textContent || elem.innerText || '')
                var val = $(elem).html().toLowerCase();
                var str = (match[3] || "").toLowerCase();
                return (val.indexOf(str) >= 0);
            }
        });
$("div:containsi('boroo')").css("text-decoration", "underline");
</script>
</body>
</html>

Saturday, November 27, 2010

Android view component code simple

public class MyMapView extends View {
private int xPos = 0; private int yPos = 0;
private Bitmap trackMap;
private Matrix backgroundMatrix;
private Paint backgroundPaint;
private Bitmap position;
private Matrix positionMatrix;
private Paint positionPaint;
public MyMapView(Context context) {
    super(context);
    init(context, null);
}
public MyMapView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
}
public MyMapView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context, attrs);
}
private void init(final Context context, AttributeSet attrs) {

backgroundMatrix = new Matrix();
backgroundPaint = new Paint();
backgroundPaint.setFilterBitmap(true);

position = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.position);
positionMatrix = new Matrix();

positionPaint = new Paint();
positionPaint.setFilterBitmap(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
}
@Override
protected void onDraw(Canvas canvas) {

    int width = getMeasuredWidth();
    int height = getMeasuredHeight();

    if (trackMap!=null)
    {
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(trackMap, height, height, true);
        canvas.drawBitmap(resizedBitmap, backgroundMatrix, backgroundPaint);

    }

        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.translate(xPos-position.getWidth()/2, yPos-position.getHeight()/2);
        canvas.drawBitmap(position, positionMatrix, positionPaint);

        canvas.restore();
}

    public void updatePosition(int xpos, int ypos, Bitmap trackImage)
    {
        xPos=xpos;
        yPos=ypos;
        trackMap = trackImage;
        invalidate();
    }
}

Android position definition ( Gravity ) of layout

public class

Gravity

extends Object
java.lang.Object
   ↳ android.view.Gravity

Class Overview

Standard constants and tools for placing an object within a potentially larger container.

Summary

Constants
int AXIS_CLIP Raw bit controlling whether the right/bottom edge is clipped to its container, based on the gravity direction being applied.
int AXIS_PULL_AFTER Raw bit controlling how the right/bottom edge is placed.
int AXIS_PULL_BEFORE Raw bit controlling how the left/top edge is placed.
int AXIS_SPECIFIED Raw bit indicating the gravity for an axis has been specified.
int AXIS_X_SHIFT Bits defining the horizontal axis.
int AXIS_Y_SHIFT Bits defining the vertical axis.
int BOTTOM Push object to the bottom of its container, not changing its size.
int CENTER Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
int CENTER_HORIZONTAL Place object in the horizontal center of its container, not changing its size.
int CENTER_VERTICAL Place object in the vertical center of its container, not changing its size.
int CLIP_HORIZONTAL Flag to clip the edges of the object to its container along the horizontal axis.
int CLIP_VERTICAL Flag to clip the edges of the object to its container along the vertical axis.
int DISPLAY_CLIP_HORIZONTAL Special constant to enable clipping to an overall display along the horizontal dimension.
int DISPLAY_CLIP_VERTICAL Special constant to enable clipping to an overall display along the vertical dimension.
int FILL Grow the horizontal and vertical size of the object if needed so it completely fills its container.
int FILL_HORIZONTAL Grow the horizontal size of the object if needed so it completely fills its container.
int FILL_VERTICAL Grow the vertical size of the object if needed so it completely fills its container.
int HORIZONTAL_GRAVITY_MASK Binary mask to get the horizontal gravity of a gravity.
int LEFT Push object to the left of its container, not changing its size.
int NO_GRAVITY Constant indicating that no gravity has been set
int RIGHT Push object to the right of its container, not changing its size.
int TOP Push object to the top of its container, not changing its size.
int VERTICAL_GRAVITY_MASK Binary mask to get the vertical gravity of a gravity.
Public Constructors
Gravity()
Public Methods
static void apply(int gravity, int w, int h, Rect container, Rect outRect)
Apply a gravity constant to an object.
static void apply(int gravity, int w, int h, Rect container, int xAdj, int yAdj, Rect outRect)
Apply a gravity constant to an object.
static void applyDisplay(int gravity, Rect display, Rect inoutObj)
Apply additional gravity behavior based on the overall "display" that an object exists in.
static boolean isHorizontal(int gravity)
Indicate whether the supplied gravity has an horizontal pull.
static boolean isVertical(int gravity)
Indicate whether the supplied gravity has a vertical pull.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final int AXIS_CLIP

Since: API Level 3
Raw bit controlling whether the right/bottom edge is clipped to its container, based on the gravity direction being applied.
Constant Value: 8 (0x00000008)

public static final int AXIS_PULL_AFTER

Since: API Level 1
Raw bit controlling how the right/bottom edge is placed.
Constant Value: 4 (0x00000004)

public static final int AXIS_PULL_BEFORE

Since: API Level 1
Raw bit controlling how the left/top edge is placed.
Constant Value: 2 (0x00000002)

public static final int AXIS_SPECIFIED

Since: API Level 1
Raw bit indicating the gravity for an axis has been specified.
Constant Value: 1 (0x00000001)

public static final int AXIS_X_SHIFT

Since: API Level 1
Bits defining the horizontal axis.
Constant Value: 0 (0x00000000)

public static final int AXIS_Y_SHIFT

Since: API Level 1
Bits defining the vertical axis.
Constant Value: 4 (0x00000004)

public static final int BOTTOM

Since: API Level 1
Push object to the bottom of its container, not changing its size.
Constant Value: 80 (0x00000050)

public static final int CENTER

Since: API Level 1
Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
Constant Value: 17 (0x00000011)

public static final int CENTER_HORIZONTAL

Since: API Level 1
Place object in the horizontal center of its container, not changing its size.
Constant Value: 1 (0x00000001)

public static final int CENTER_VERTICAL

Since: API Level 1
Place object in the vertical center of its container, not changing its size.
Constant Value: 16 (0x00000010)

public static final int CLIP_HORIZONTAL

Since: API Level 3
Flag to clip the edges of the object to its container along the horizontal axis.
Constant Value: 8 (0x00000008)

public static final int CLIP_VERTICAL

Since: API Level 3
Flag to clip the edges of the object to its container along the vertical axis.
Constant Value: 128 (0x00000080)

public static final int DISPLAY_CLIP_HORIZONTAL

Since: API Level 3
Special constant to enable clipping to an overall display along the horizontal dimension. This is not applied by default by apply(int, int, int, Rect, int, int, Rect); you must do so yourself by calling applyDisplay(int, Rect, Rect).
Constant Value: 16777216 (0x01000000)

public static final int DISPLAY_CLIP_VERTICAL

Since: API Level 3
Special constant to enable clipping to an overall display along the vertical dimension. This is not applied by default by apply(int, int, int, Rect, int, int, Rect); you must do so yourself by calling applyDisplay(int, Rect, Rect).
Constant Value: 268435456 (0x10000000)

public static final int FILL

Since: API Level 1
Grow the horizontal and vertical size of the object if needed so it completely fills its container.
Constant Value: 119 (0x00000077)

public static final int FILL_HORIZONTAL

Since: API Level 1
Grow the horizontal size of the object if needed so it completely fills its container.
Constant Value: 7 (0x00000007)

public static final int FILL_VERTICAL

Since: API Level 1
Grow the vertical size of the object if needed so it completely fills its container.
Constant Value: 112 (0x00000070)

public static final int HORIZONTAL_GRAVITY_MASK

Since: API Level 1
Binary mask to get the horizontal gravity of a gravity.
Constant Value: 7 (0x00000007)

public static final int LEFT

Since: API Level 1
Push object to the left of its container, not changing its size.
Constant Value: 3 (0x00000003)

public static final int NO_GRAVITY

Since: API Level 1
Constant indicating that no gravity has been set
Constant Value: 0 (0x00000000)

public static final int RIGHT

Since: API Level 1
Push object to the right of its container, not changing its size.
Constant Value: 5 (0x00000005)

public static final int TOP

Since: API Level 1
Push object to the top of its container, not changing its size.
Constant Value: 48 (0x00000030)

public static final int VERTICAL_GRAVITY_MASK

Since: API Level 1
Binary mask to get the vertical gravity of a gravity.
Constant Value: 112 (0x00000070)

Public Constructors

public Gravity ()

Since: API Level 1

Public Methods

public static void apply (int gravity, int w, int h, Rect container, Rect outRect)

Since: API Level 1
Apply a gravity constant to an object.
Parameters
gravity The desired placement of the object, as defined by the constants in this class.
w The horizontal size of the object.
h The vertical size of the object.
container The frame of the containing space, in which the object will be placed. Should be large enough to contain the width and height of the object.
outRect Receives the computed frame of the object in its container.

public static void apply (int gravity, int w, int h, Rect container, int xAdj, int yAdj, Rect outRect)

Since: API Level 1
Apply a gravity constant to an object.
Parameters
gravity The desired placement of the object, as defined by the constants in this class.
w The horizontal size of the object.
h The vertical size of the object.
container The frame of the containing space, in which the object will be placed. Should be large enough to contain the width and height of the object.
xAdj Offset to apply to the X axis. If gravity is LEFT this pushes it to the right; if gravity is RIGHT it pushes it to the left; if gravity is CENTER_HORIZONTAL it pushes it to the right or left; otherwise it is ignored.
yAdj Offset to apply to the Y axis. If gravity is TOP this pushes it down; if gravity is BOTTOM it pushes it up; if gravity is CENTER_VERTICAL it pushes it down or up; otherwise it is ignored.
outRect Receives the computed frame of the object in its container.

public static void applyDisplay (int gravity, Rect display, Rect inoutObj)

Since: API Level 3
Apply additional gravity behavior based on the overall "display" that an object exists in. This can be used after apply(int, int, int, Rect, int, int, Rect) to place the object within a visible display. By default this moves or clips the object to be visible in the display; the gravity flags DISPLAY_CLIP_HORIZONTAL and DISPLAY_CLIP_VERTICAL can be used to change this behavior.
Parameters
gravity Gravity constants to modify the placement within the display.
display The rectangle of the display in which the object is being placed.
inoutObj Supplies the current object position; returns with it modified if needed to fit in the display.

public static boolean isHorizontal (int gravity)

Since: API Level 1
Indicate whether the supplied gravity has an horizontal pull.
Parameters
gravity the gravity to check for horizontal pull
Returns
  • true if the supplied gravity has an horizontal pull

public static boolean isVertical (int gravity)

Since: API Level 1
Indicate whether the supplied gravity has a vertical pull.
Parameters
gravity the gravity to check for vertical pull
Returns
  • true if the supplied gravity has a vertical pull

Friday, November 26, 2010

Android same capability or methods


  1. Toast.makeText(this, "activity canceled", Toast.LENGTH_SHORT).show();           энэ method нь Tooltip текст шиг түр хугацаанд гарч ирээд алга болно.

  2. View v = activity.getViewInflate().inflate(R.layout.buttons, null, null);
      Button b = (Button)v.findViewById(R.id.button_small_left);               энэ жишээ кодыг ашиглаж *layout.xml дотор үүсгэсэн Button гэх мэт компонентоо авч өөрийнхөө Current Activity -д ашиглах боломжтой юм.
  3. Log.i, Log.d, Log.e, Log.i
    int ASSERT Priority constant for the println method.
    int DEBUG Priority constant for the println method; use Log.d.
    int ERROR Priority constant for the println method; use Log.e.
    int INFO Priority constant for the println method; use Log.i.
    int VERBOSE Priority constant for the println method; use Log.v.
    int WARN Priority constant for the println method; use Log.w.
     
  4. int resourceId = Activity.getResources().getIdentifier("imagename", "drawable", "your.package.name"); энэ чадварыг ашиглан resourse нэрээр Id -г авах боломжтой болно. Жишээ нь:
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId); 
    imageView.setImageBitmap(bitmap);

    Wednesday, November 24, 2010

    @Android:id features ( different syntax of id attr )

    Android дээр програм бичих явцад зарим компонент (components) ууд нь тогтмол id тай байх шаардлагатай байдаг.         android:id="@android:id/tabhost" or more         гэх мэтчилэн.
    Учир нь Android систем маань ингэж нэрлэгдсэн ( урьчилан бэлдсэн үйлдэлийг агуулж байгаа конпонентуудийн ) тохиргоог уншиж компонентийг үүсгэдэг ба хөгжүүлэгч энэ тохиолдолд компонентийг дэлгэрүүлэн сайжруулах боломжтой юм. Бидний ойлгож заншсанаар *.xml файл доторхи ингэж (@android:id/tabhost хэлбэрээр) бичигдсэн тохиргоо нь Template маягийн үүргийг системд гүйцэтгэдэг гэж төсөөлж болно. Эсрэг тохиолдол бид өөрийн хүссэнээр android:id="@+id/myComponentId" кодыг бичиж id -аар нь хандаж ажилладаг.

    Урьдчилан бэлдэгдсэн үйлдэлтэй компонентуудын тогтмол @android:id -ний жагсаалтыг доорхи xml -д үзүүлж байна. Ө.Х @android:id -жагсаалтаас өөр нэр өгвөл алдаа заана гэсэн үг юм.


    <?xml version="1.0" encoding="utf-8"?>
    <!--
    **
    ** Copyright 2007, The Android Open Source Project
    **
    ** Licensed under the Apache License, Version 2.0 (the "License");
    ** you may not use this file except in compliance with the License.
    ** You may obtain a copy of the License at
    **
    **     http://www.apache.org/licenses/LICENSE-2.0
    **
    ** Unless required by applicable law or agreed to in writing, software
    ** distributed under the License is distributed on an "AS IS" BASIS,
    ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    ** See the License for the specific language governing permissions and
    ** limitations under the License.
    */
    -->
    <resources>
      <item type="id" name="background" />
      <item type="id" name="checkbox" />
      <item type="id" name="content" />
      <item type="id" name="empty" />
      <item type="id" name="hint" />
      <item type="id" name="icon" />
      <item type="id" name="icon1" />
      <item type="id" name="icon2" />
      <item type="id" name="input" />
      <item type="id" name="left_icon" />
      <item type="id" name="list" />
      <item type="id" name="menu" />
      <item type="id" name="message" />
      <item type="id" name="primary" />
      <item type="id" name="progress" />
      <item type="id" name="right_icon" />
      <item type="id" name="summary" />
      <item type="id" name="selectedIcon" />
      <item type="id" name="tabcontent" />
      <item type="id" name="tabhost" />
      <item type="id" name="tabs" />
      <item type="id" name="text1" />
      <item type="id" name="text2" />
      <item type="id" name="title" />
      <item type="id" name="title_container" />
      <item type="id" name="toggle" />
      <item type="id" name="secondaryProgress" />
      <item type="id" name="lock_screen" />
      <item type="id" name="edit" />
      <item type="id" name="widget_frame" />
      <item type="id" name="button1" />
      <item type="id" name="button2" />
      <item type="id" name="button3" />
      <item type="id" name="extractArea" />
      <item type="id" name="candidatesArea" />
      <item type="id" name="inputArea" />
      <item type="id" name="inputExtractEditText" />
      <item type="id" name="selectAll" />
      <item type="id" name="cut" />
      <item type="id" name="copy" />
      <item type="id" name="paste" />
      <item type="id" name="copyUrl" />
      <item type="id" name="switchInputMethod" />
      <item type="id" name="keyboardView" />
      <item type="id" name="closeButton" />
      <item type="id" name="startSelectingText" />
      <item type="id" name="stopSelectingText" />
      <item type="id" name="addToDictionary" />
      <item type="id" name="accountPreferences" />
      <item type="id" name="smallIcon" />
    </resources>

    Tuesday, November 23, 2010

    Android WebView and WebViewClient example

    private static void initWebkit(WebView web, WidgetActivity activity) {
    
      final String mimetype = "text/html";
      final String encoding = "UTF-8";
      String htmldata = "<html><body>boo</body></html>";
    
      {
        String data = ResourceUtils.loadResToString(R.raw.content, activity);
        if (data != null) htmldata = data;
      }
    
      web.loadData(htmldata,
                   mimetype,
                   encoding); 
     
    web.setWebViewClient(new WebViewClient() { 
     
    @Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
          Log.i(Global.TAG, "Panel2Builder... webview URL:" + url);
    
          if (url.contains("clock")) {
            String html = "<html><body>Date:" + new Date().toString() + "</body></html>";
            view.loadData(html, mimetype, encoding);
            Log.i(Global.TAG, "Panel2Builder intercepting webview url click...");
            return true;
          }
          else {
            Log.i(Global.TAG, "Panel2Builder not processing webview url click...");
            return false;
          }
    
        }
      });
     
    }

    How to develop android using java code for beginner

    Java хэлийг ашиглан android mobile application хийх тухай зөвлөгөө жишээ. Хаалтан дотор гэнэт англи монгол хольж бичсэн байвал давхар тайлбарлаж байна гээд ойлгоорой!

    Аль editor байсан гэсэн (intellij, netbeans, eclipse) android хөгжүүлэхэд дараах файл, сангууд дээр түлхүү ажиллана.

    1. AndroidManifest.xml файлд програмын үндсэн тохиргоо байна.
    2. res санд програмын нөөцүүд (зураг, бэлдэц текст, layout - байршил) байрлана.
    3. src санд java кодууд (Activity and more) байна. 
    Android mobile application ажиллахдаа:

    AndroidManifest.xml файлаас тохиргоогоо уншиж эхэнд ажиллуулах үйл ажиллагаа (Activity) -г тохируулсаны дагуу нэртэй, харагдах тексттэй, icon файлтайгаар дуудаж ачааллана. Ачаалсан Activity нь өөртөө layout (хар үгээр байршуулагч конпонент) -г агуулдаг ба энэ нь Activity -д байрших элдэв (компонент, контрол, контент) -г агуулна. Layout тодор тодорхойлогдсон компонентууд утсан дээр чинь харагдана гэж төсөөлөх хэрэгтэй. Android app -ийн Кодын бүтцийг дараах зургаар төсөөлөн үзүүлье.

    Activity дотор Layout (Жишээ нь LinearLayout - аль нэг чиглэлд шугаман байрлана хөндлөн, босоо ч юм уу)





    Layout дотор Контролуудыг (EditText, Button, ListView, ImageView) нэмнэ. Мэдээж код нь new LinearLayout() гээд бичигдэнэ. Цаашаа нь layout.addView(button);

    тэгээд button.addOnClickListener эсвэл Activity - н Override method (чадваруудыг ашиглана болно)







     Жишээ нь:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_CALL) {
                performDial();
                return true;
            } else if (keyCode == KeyEvent.KEYCODE_0) {
                performAbout();
                return true;
            }
            return false;
        }

     гэх мэтчилэн код бичиж болно. Энэ бол зөвхөн санаа юм.


     За одоо нэг жишээ жижигхэн програм дээр авч үзье. Сайн ажиглаарай!

    Жишээ нь:
    Жишээний хийх үйлдэл нь нэг Activity -аас нөгөө Activity -г дуудаж ажиллуулаад утгыг нь авах.


    AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="com.sodonsolution.android">


        <application android:icon="@drawable/icon" android:label="@string/app_name">
            <activity android:name=".FirstAct" android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
            <activity android:name=".SecondAct" android:label="Request Here"/>
        </application>


    </manifest>


    Тохиргоотой байвал энэ xml файлд Android app маань 2 Activity -тай эхлэж ажиллахдаа src/PackageName/FirstAct.java файл ачааллах болно.


    FirstAct.java

    package com.company.android;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.Toast;

    public class FirstAct extends Activity
    {
        private static final int INPUT_REQUEST = 0;

        //Загвар класс ашиглан Event класс үүсгэж байна
        private class ButtonHandler implements View.OnClickListener
        {
            public void onClick(View v)
            {
                handleButtonClick();
            }
        }
       
        //Activity -г ачаалахад эхэлж дуудагддаг method ( чадвар )
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);

            // Шинэ компонент үүсгэж байна
            Button startAct = new Button(this);
            startAct.setText("Start Activity");

            // Шинэ компонент байршуулагч өөр дээрээ үүсгэж байна.
            LinearLayout layout = new LinearLayout(this);

            // Одоо үүсгэсэн Button компонентоо байршуулж байна
            layout.addView(startAct, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // Компенентодоо Event өгч байна
            startAct.setOnClickListener(new ButtonHandler());

            // Үүсгэсэн байршилаа өөртөө өгч байна Activity маань.
            setContentView(layout);

            //Ингээд үр дүнд нь Button харагдах болно. Энэ нь xml тохиргоогоор биш кодоор үүсгэж байгаа жишээ юм. Энэ үгийг анхаар xml нөөцөөр бас үүсгэж болдог байх нь.
            //нэг setContentView(R.layout.main); иймэрхүү
        }

        private void handleButtonClick()
        {

              //Intent class SecondAct параметртай үүсгэж байна. Ө.Х SecondAct Activity -г дуудаж байна
              //startActivityForResult, startActivity method бол ер нь Activity -г ачаалдаг чадварууд юм.
              //startActivityForResult нь нэг ялгаа нь дуудаад буцах утгыг нь авахад зориулагдсан
              startActivityForResult(new Intent(this, SecondAct.class), INPUT_REQUEST);
        }
       
        //Доорхи method нь програмын цонх ажиллаж дуусаад ямар үйлдэл хийгдэснийг мэдрэх зорилготой. Жишээ нь 2 Activity хоорондоо мэдээлэл дамжуулах эсвэл ачаалсан Activity маань ажиллаж дуусахдаа ямар төлөвтэй болсон ( програмыг cancel д чихлаа гэдгийг мэдэж болно ) зэргийг мэдээлэх үүрэгтэй юм.
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == Activity.RESULT_CANCELED)
                Toast.makeText(this, "activity canceled", Toast.LENGTH_SHORT).show();
            else if (resultCode == Activity.RESULT_OK)
            {
                String input = data.getStringExtra("input");
                Toast.makeText(this, "input = " + input, Toast.LENGTH_SHORT).show();
            }
        }
    }




    SecondAct.java



    package com.sodonsolution.android;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.LinearLayout;

    public class SecondAct extends Activity
    {
        private EditText input = null;
        private Button okay = null;

        private class ButtonOkayHandler implements View.OnClickListener
        {
            public void onClick(View v)
            {
                handleOkayButton();
            }
        }

        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);

            // initializing the fields
            input = new EditText(this);
            input.setText("Enter text here ...");
            okay = new Button(this);
            okay.setText("Okay");

            // defining the layout in code instead of XML
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.addView(input, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            layout.addView(okay, new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));

            // activating the button
            okay.setOnClickListener(new ButtonOkayHandler());

            // setting the view to our layout
            setContentView(layout);
        }

        private void handleOkayButton()
        {

            //Activity нь ихэвчлэн Intent буюу зорилго болсон нэг классаар хандаж ажилладаг. Энэ Intent класс д л элдэв өгөгдөл тэр битгий хэл Activity -г ч хүртэл өгч ачаалахад ашиглаж байгааг FirstAct.java аас олж хараарай!
            Intent data = new Intent();
            data.putExtra("input", input.getText().toString());

            //Activity маань буцах утгыг оноож байна
            setResult(Activity.RESULT_OK, data);




            //Activity -ийн ажиллагааг дуусгаж байна. Цонх хааж байна гэж ойлгож болно
            finish();
        }
    }











    Дээрхи жишээн дээр кодоор компонент үүсгэж ашиглаж байсан бол одоо бол XML тохиргооний файл ашиглан програмтай бүтээх тухай жаахан жишээ хэлье.




    Android Project үүсгэсний дараа res гэсэн сан үүснэ. Түүнд layout, drawable, values or resource гэсэн дэд сангууд байна.
    1. layout санд байх xml файлууд нь бидний түрүүн кодоор хийгээд байсан компенентуудыг бэлдэх зорилготой юм. Нэг xml файл нь нэг Activity гэж ойлгож болно. Бүх байршилыг нь xml дээр нарийн зааж өгөөд дараа нь код дээрээ ашиглахдаа setContentView(R.layout.xmlFiletitle); гэж бичихэд компонентууд байрших болно. Нэгэнт xml ээр үүсчихсэн контролыг id attribute-аар нь объект болгон авч болно. Жишээ нь: Button mButton = (Button) findViewById(R.id.myButtonId0);      мөн жаахан нэмэн дэлгэрүүлээд mButton.setOnClickListener(new View.OnClickListener(){
                  public void onClick(View view) {
                      String name = getIntent().getStringExtra("name");
                      getIntent().putExtra("name", "Hello, " + name);
                      setResult(Activity.RESULT_OK);
                  }
              });
             Event өгч болно. Ингэж xml -ээр үүсгэсэн объектоо баяжуулна.
    2. drawable санд байгаа файлууд мөн л ижил хэрэгжинэ. Ер нь өөрийн дураар илүү олон санд файлуудаа байршуулж болно. Хандаж авахдаа харин R класс дотор үүссэн байгаа нэрээрээ хандаж авна. Нөөцийн санд байгаа файл болон утгууд нь R класс дотор ялгаатай нэрээр бүртгэгддэг гэдгийг сайн анхаараарай!
    3. values сан дотор байгаа тохиргоон дээр харж байгаад дуурай өөрийн хүссэнээр шинэ утга нэмж болно. Харин өөр газар ашиглагдаж байгаа утгыг устгавал мэдээж алдаа заана. Жишээ нь: values/strings.xml тохиргоо дотор <?xml version="1.0" encoding="utf-8"?>
      <resources>
          <string name="hello">Welcome, Guest!</string>
          <string name="app_name">news.mn</string>
          <string name="aboutus">Бидний тухай</string>
      </resources>

      гэж бичээд ашиглахдаа кодонд setText(R.string.aboutus); layout/*.xml файлд <TextView android:id="@+id/dateDisplay"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="@string/hello"/>
      гэж android:text="@string/hello" гэх мэтчилэн ашиглаж болно.
    Android -г java хэлэн дээр хөгжүүлэх их хялбар боллоо. Амжилт хүсье