** 7가지 EventHandler **

 

1. 프로젝트명 : ClickEvent

 

2. 정의 : EventHandler 종료

 

3. 소스명 :

    1. MainActivity.java

    2. ClickHandler.java

    3. activity_main.java

 

4. 안드로이드 버전

     - 스튜디오 : v2.2.3

     - Minumum SDK : API 19:Android 4.4. (KitKat)

 

5. 화면

    

 

 

5. 설명

    1. 익명 내부 클래스 처리
    2. 유명 내부 클래스 처리
    3. 유명 내부 클래스
    4. 제3클래스로 처리
    5. 자신의 클래스로 처리
    6. XML에서 핸들러 이벤트 저장
    7. 유명 외부 메소드

 

 

  1. MainActivity.java

 

package com.example.farmer.clickevent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btn1;
    Button btn2;
    Button btn3;
    Button btn4;
    Button btn5;
    Button btn6;
    Button btn7;
    EditText et01;

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

        btn1 = (Button)findViewById(R.id.btn01);
        btn2 = (Button)findViewById(R.id.btn02);
        btn3 = (Button)findViewById(R.id.btn03);
        btn4 = (Button)findViewById(R.id.btn04);
        btn5 = (Button)findViewById(R.id.btn05);
        btn6 = (Button)findViewById(R.id.btn06);
        btn7 = (Button)findViewById(R.id.btn07);
        et01 = (EditText)findViewById(R.id.editText01);

        //1. 익명 내부 클래스 : 클래스 이름이 없다.
        //   일회성 : 한번만 쓸 때 사용
        btn1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                et01.setText("1. 익명 내부 클래스 처리");
                showToast("1. 익명 내부 클래스 처리");
            }
        });

        //2. 유명 내부 클래스
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et01.setText("2. 유명 내부 클래스 처리");
                showToast("2. 유명 내부 클래스 처리");
            }
        };
        btn2.setOnClickListener(onClickListener);

        //3. 유명 내부 클래스
        btn3.setOnClickListener(new InnerHandler());

        //4. 제3클래스로 처리
        btn4.setOnClickListener(new ClickHandler(MainActivity.this));

        //5. 자신의 클래스로 처리
        //   이건   [public class MainActivity extends AppCompatActivity implements View.OnClickListener]
        //          이렇게 함으로써 처리 됨
        //   아래 [public void onClick(View view) { ] 와 연결 됨
        btn5.setOnClickListener(this);

        //7.
        btn7.setOnClickListener(onClickListener7);
    }

    //3. 유명 내부 클래스
    class InnerHandler implements View.OnClickListener{
        public void onClick(View view) {
            et01.setText("3. 유명 내부 클래스 처리");
            showToast("3. 유명 내부 클래스 처리");
        }
    }

    //5. 자신의 클래스로 처리
    //   이건   [public class MainActivity extends AppCompatActivity implements View.OnClickListener]
    //          이렇게 함으로써 처리 됨
    //   위쪽 [btn5.setOnClickListener(this);] 이 script로 연결됨
    @Override
    public void onClick(View view) {
        et01.setText("5. 자신의 클래스로 처리");
        showToast("5. 자신의 클래스로 처리");
    }

    //6. XML에서 핸들러 이벤트 저장
    public void xmlHandlerMethod(View view){
        et01.setText("6. XML에서 핸들러 이벤트 저장");
        showToast("6. XML에서 핸들러 이벤트 저장");
    }

    //7. 유명 외부 메소드
    private  View.OnClickListener onClickListener7 = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            et01.setText("7. 유명 외부 메소드");
            showToast("7. 유명 외부 메소드");
        }
    };


    public void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}

 

 

 

 

  2. CllickHandler.java

 

package com.example.farmer.clickevent;

import android.view.View;

/**
* Created by farmer on 2017-01-07.
*/

public class ClickHandler implements View.OnClickListener {
    MainActivity activity;

    public ClickHandler(MainActivity activity) {
        this.activity = activity;
    }

    @Override
    public void onClick(View view) {
        activity.et01.setText("4. 제3클래스로 처리");
        activity.showToast("4. 제3클래스로 처리");
    }
}

 

 

 

  3. activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.farmer.clickevent.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="30dp"
        android:text="OnClickEvent"
        android:id="@+id/textView" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn01"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="버튼 1"/>

        <Button
            android:id="@+id/btn06"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="xmlHandlerMethod"
            android:text="버튼 6 (xml)"/>
    </LinearLayout>

    <Button
        android:id="@+id/btn02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="버튼 2"/>
    <Button
        android:id="@+id/btn03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="버튼 3"/>
    <Button
        android:id="@+id/btn04"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="버튼 4"/>
    <Button
        android:id="@+id/btn05"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="버튼 5"/>
    <Button
        android:id="@+id/btn07"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="버튼 7"/>

    <EditText
        android:id="@+id/editText01"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:editable="false"
        android:hint="hint"/>
</LinearLayout>

 

Posted by 농부지기
,

** 사칙연산(괄호 가능) **

0. 프로젝트명 : KeyPadAll

1. 사칙연산을 Queue에 넣다 빼면서 처리

2. 괄호 가능

3. 화면 :

   

 

5. 안드로이드 버전

     - 스튜디오 : v2.2.3

     - Minumum SDK : API 19:Android 4.4. (KitKat)

 

6. 소스목록

   1. MainActivity.java
   2. Calculator.java
   3. activity_main.xml
   4. drawable/border_calbutton.xml
   5. drawable/border_layout.xml
   6. values/colors.xml

 

6. 소스

 

1. MainActivity.java

 

package com.example.farmer.keypadall;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    EditText arithmetic;
    TextView result;

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

        arithmetic = (EditText)findViewById(R.id.et_arithmetic);
        result      = (TextView)findViewById(R.id.tv_result);

        ((TextView)findViewById(R.id.tv_mqrquee)).setSelected(true);

        //arithmetic.requestFocus();  //포커스 주기
        arithmetic.setFocusableInTouchMode(false); // 결과 box에 edit막기 : ok
        arithmetic.setKeyListener(null);  //key 가 안눌림. 하지만 keypad가 보임
    }

    //---------------------------------------------------------------------------
    // 사칙연산자 클릭 시
    //   - 사칙연산자가 중복 시 최종연산자로 대체
    //---------------------------------------------------------------------------
    public void arithmeticOrganOnClick(View view){
        String sCurrNum = arithmetic.getText().toString();

        if (sCurrNum.length() == 0return;

        String lastChar = sCurrNum.substring(sCurrNum.length()-1, sCurrNum.length());
        if ("+-*/".indexOf(lastChar) >= 0){
            arithmetic.setText( sCurrNum.substring(0, sCurrNum.length()-1) + ((Button)view).getText());
        }else{
            arithmetic.setText( sCurrNum + ((Button)view).getText());
        }
    }

    //---------------------------------------------------------------------------
    //  숫자 클릭 시
    //---------------------------------------------------------------------------
    public void numberOnClick(View view){
        arithmetic.setText( arithmetic.getText().toString() + ((Button)view).getText());
    }
    //---------------------------------------------------------------------------
    //  소수점 클릭 시
    //---------------------------------------------------------------------------
    public void pointOnClick(View view){
        arithmetic.setText( arithmetic.getText().toString() + ((Button)view).getText());
    }

    //---------------------------------------------------------------------------
    //  BackClear 버튼 클릭 시
    //---------------------------------------------------------------------------
    public void oneCharClearOnClick(View view){
        String sCurrNum = arithmetic.getText().toString();  //? getText() : Return이 Editable ?

        //Log.d("farm-1", sNum1);  //?log가 안보임 ?
        if (sCurrNum.length() > 0) {
            //Log.d("farm-2", sNum1);
            sCurrNum = sCurrNum.substring(0, sCurrNum.length() - 1);
            //Log.d("farm-3", sNum1);
            arithmetic.setText(sCurrNum);

            //포커스를 맨 뒤로 하기
            //Editable editable = arithmetic.getText();
            //Selection.setSelection(editable, editable.length());
        }
    }

    //---------------------------------------------------------------------------
    //  Clear 버튼 클릭 시
    //---------------------------------------------------------------------------
    public void allClearOnClick(View view){
        arithmetic.setText("");
        result.setText("");
    }

    //---------------------------------------------------------------------------
    // ()괄호 버튼 클릭 시
    // 1. 숫자 다음에 (  여는 괄호는 올 수 없음
    // 2. 사칙연산자 다음이 ) 닫는 괄호는 올 수 없음
    //---------------------------------------------------------------------------
    public void bracketOnclick(View view){
        String sCurrNum = arithmetic.getText().toString();

        switch (view.getId()){
            case R.id.bt_braketLeft:
                if (sCurrNum.length() > 0) {
                    String lastChar = sCurrNum.substring(sCurrNum.length()-1, sCurrNum.length());
                    Toast.makeText(MainActivity.this, "lastChar=" + lastChar, Toast.LENGTH_SHORT).show();
                    if ("0123456789".indexOf(lastChar) >= 0) return;
                }
                break;
            case R.id.bt_braketRight:
                if (sCurrNum.length() > 0) {
                    String lastChar = sCurrNum.substring(sCurrNum.length()-1, sCurrNum.length());
                    if ("+0*/".indexOf(lastChar) >= 0) return;
                }
                break;
        }

        arithmetic.setText( arithmetic.getText().toString() + ((Button)view).getText());
    }

    //---------------------------------------------------------------------------
    //  계산 버튼 클릭 시
    //---------------------------------------------------------------------------
    public void calculatorOnClick(View view) throws Exception{
        Calculator calculator = new Calculator();

        String sCurrNum = arithmetic.getText().toString();
        String resultVal = calculator.bracketCalMain(sCurrNum);
        result.setText(resultVal);
    }
}

 

 

2. Calculator.java

 

package com.example.farmer.keypadall;

import java.util.LinkedList;
import java.util.Queue;
import java.math.BigDecimal;

/**
* Created by kyh on 2017-01-02.
*/

public class Calculator {
    //------------------------------------------------------------------------
    // 괄호 까지 존재하는 사칙연사
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static String bracketCalMain(String sNumList) throws Exception{
        //0. ( ) 괄호 갯수 검증
        if (checkBracket(sNumList) == false) return "괄호 () 갯수가 Match되지 않습니다.";

        // 1. 1차 문자열 Parsing
        Queue firstQueue = new LinkedList();
        firstQueue = stringParsing(sNumList);
        System.out.println("----------------------------------------------");
        System.out.println("괄호 1차  => " + firstQueue.toString());

        // 2. 2차 괄호안 계산
        Queue secondQueue = new LinkedList();
        String oneChar;
        while(firstQueue.peek() != null){
            oneChar  = firstQueue.poll().toString();
            //System.out.println("괄호  => " + oneChar);

            if ("()".indexOf(oneChar) >= 0){
                //괄호안 계산 (firstQueue)
                secondQueue.offer(braketInCal(firstQueue));
            }else{
                secondQueue.offer(oneChar);
            }
        }

        //3. Queue에 저장 된 값 중  곱셈. 나눗셈 계산
        secondQueue = multiplyDivideCal(secondQueue);

        //4. Queue에 저장 된 값 중  덧셈. 뺄샘 계산
        String sResult = addSubtractCal(secondQueue);
        System.out.println("괄호 최종결과 => " + sResult);
        return sResult;
    }

    //( ) 괄호 갯수 검증
    public static boolean checkBracket(String sNumList){
        int count1=0, count2=0;
        for(int i=0; i<sNumList.length(); i++){
            if ("(".equals(sNumList.substring(i, i+1))){
                count1 ++;
            }else if (")".equals(sNumList.substring(i, i+1))){
                count2 ++;
            }
        }

        if (count1 == count2)
            return true;
        else{
            System.out.println("괄호 () 갯수가 Match되지 않습니다.");
            return false;
        }
    }

    //------------------------------------------------------------------------
    // 1차. 문자열 Parsing
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Queue stringParsing(String sNumList){
        String sOneNum = ""//하나의 숫자열
        Queue firstQueue = new LinkedList();
        for(int i=0; i<sNumList.length(); i++){
            String oneChar = sNumList.substring(i, i+1);
            if ("+-*/()".indexOf(oneChar) >= 0 ){

                // 3+(3  과 같이   4칙연산자와 괄호가 동시에 존재 하는 경우 때문
                if (!"".equals(sOneNum)) firstQueue.offer(sOneNum);   
                firstQueue.offer(oneChar);
                sOneNum = "";
            }else{
                sOneNum += oneChar;

                if (i+1 == sNumList.length()){
                    firstQueue.offer(sOneNum);
                }
            }
        }
        return firstQueue;
    }

    //------------------------------------------------------------------------
    // 2차. 괄호 내부 계산 (재귀적 호출)
    //------------------------------------------------------------------------
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static String braketInCal(Queue firstQueue) throws Exception{
        String oneChar;
        //1. 괄호 내부에 존재 하는 값을 Queue에 저장
        Queue secondQueue = new LinkedList();
        while(firstQueue.peek() != null){
            oneChar  = firstQueue.poll().toString();
            if ("(".equals(oneChar)){
                //괄호안 계산 (firstQueue)
                secondQueue.offer(braketInCal(firstQueue));
            }else if (")".equals(oneChar)){
                break; //닫기 괄호가 나오면 stop
            }else{
                secondQueue.offer(oneChar);
            }
        }
        System.out.println("괄호 2차  => " + secondQueue.toString());

        //2. Queue에 저장 된 값 중  곱셈. 나눗셈 계산
        secondQueue = multiplyDivideCal(secondQueue);

        //3. Queue에 저장 된 값 중  덧셈. 뺄샘 계산
        String sResult = addSubtractCal(secondQueue);

        return sResult;
    }


    //------------------------------------------------------------------------
    // 곱셈, 나눗셈 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Queue multiplyDivideCal(Queue inQueue) throws Exception{
        Queue outQueue = new LinkedList();
        String oneChar;
        String sNum1 = "", sNum2 = "", sResult = "";
        String operator = "";
        BigDecimal nResult = new BigDecimal("0");
        while(inQueue.peek() != null){
            oneChar  = inQueue.poll().toString();

            if ("+-".indexOf(oneChar) >= 0 ){
                outQueue.offer(sNum1);
                outQueue.offer(oneChar);
                sNum1 = "";
            }else if ("*/".indexOf(oneChar) >= 0 ) {
                operator = oneChar;
            }else{
                if ("".equals(sNum1)){
                    sNum1 = oneChar;
                }else if ("".equals(sNum2)) {
                    sNum2 = oneChar;
                    if ("*".equals(operator)) {
                        nResult = (new BigDecimal(sNum1)).multiply(new BigDecimal(sNum2));
                    }else if ("/".equals(operator)) {
                        if ("0".equals(sNum2)){
                            throw new Exception("나눗셈 분모에 0 이 존재 합니다.");
                        }

                        nResult = (new BigDecimal(sNum1)).divide(new BigDecimal(sNum2), 6, BigDecimal.ROUND_UP);
                    }
                    sResult  = String.valueOf(nResult);


                    sNum1    = sResult;
                    sNum2    = "";
                    operator = "";
                }
            }

            if (inQueue.peek() == null) outQueue.offer(sNum1);
        }
        return outQueue;
    }


    //------------------------------------------------------------------------
    // 덧셈. 뺄샘 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes" })
    public static String addSubtractCal(Queue inQueue){
        String operator = "";
        String oneChar  = "";
        BigDecimal nResult  = new BigDecimal(inQueue.poll().toString());
        while(inQueue.peek() != null){
            oneChar  = inQueue.poll().toString();

            if ("+-".indexOf(oneChar) >= 0 ){
                operator = oneChar;
            }else{
                if ("+".equals(operator)){
                    nResult = nResult.add(new BigDecimal(oneChar));
                }else if ("-".equals(operator)){
                    nResult = nResult.subtract(new BigDecimal(oneChar));
                }
                operator = "";
            }
        }
        return nResult.toString();
    }
}

 

 

 

3. activity_main.xml 

 

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

    android:id="@+id/activity_keypad"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d1cdcd"
    android:orientation="vertical"
    tools:context="com.example.farmer.keypadall.MainActivity">

    <!--   0차 : mqrquee -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#00ffffff"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_mqrquee"
            android:textSize="30dp"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="농부의 4칙연산 계산기. 자체개발 완료..  으미 힘든거~~~~~~"
            android:ellipsize="marquee"
            android:focusable="true"
            android:marqueeRepeatLimit="marquee_forever"
            android:singleLine="true"/>
    </RelativeLayout>
    <!--  1차 : 산술식 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#b4b2b7"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_num"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="4칙 연산식"/>

        <EditText
            android:id="@+id/et_arithmetic"
            android:layout_marginRight="10dp"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:hint="4칙 연산식을 입력 하시오."
            android:paddingLeft="10dp"
            android:background="#ffffff"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_num" />

    </RelativeLayout>

    <!--   2차 : 결과 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#d7c6ed"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_resultLabel"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_alignParentLeft="true"
            android:text="Result"/>

        <TextView
            android:id="@+id/tv_result"
            android:textSize="20dp"
            android:layout_marginRight="10dp"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:text=""
            android:paddingLeft="10dp"
            android:background="#e4e4dd"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_resultLabel"/>

    </RelativeLayout>

    <!--   3차 : 빈 공백 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#fcfcfc"
        android:layout_weight="0.2">
    </RelativeLayout>

    <!--   4차 : 기타   C, ( ) /   "#6a00ff" -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/border_layout"
        android:layout_weight="1">

        <Button
            android:id="@+id/bt_clear"
            android:onClick="allClearOnClick"
            android:text="C"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_marginLeft="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>
        <Button
            android:id="@+id/bt_braketLeft"
            android:onClick="bracketOnclick"
            android:text="("
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_clear"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>
        <Button
            android:id="@+id/bt_braketRight"
            android:onClick="bracketOnclick"
            android:text=")"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_braketLeft"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>
        <Button
            android:id="@+id/bt_divide"
            android:onClick="arithmeticOrganOnClick"
            android:text="/"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_braketRight"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>

    </RelativeLayout>

    <!--   5차 : 7,8,9, *  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/border_layout"
        android:layout_weight="1">

        <Button
            android:id="@+id/bt_seven"
            android:onClick="numberOnClick"
            android:text="7"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_eight"
            android:onClick="numberOnClick"
            android:text="8"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_seven"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_nine"
            android:onClick="numberOnClick"
            android:text="9"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_eight"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_multiply"
            android:onClick="arithmeticOrganOnClick"
            android:text="*"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_nine"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>

    </RelativeLayout>

    <!--   6차 : 4,5,6,-  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/border_layout"
        android:layout_weight="1">

        <Button
            android:id="@+id/bt_four"
            android:onClick="numberOnClick"
            android:text="4"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_five"
            android:onClick="numberOnClick"
            android:text="5"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_four"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_six"
            android:onClick="numberOnClick"
            android:text="6"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_five"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_minus"
            android:onClick="arithmeticOrganOnClick"
            android:text="-"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_six"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>

    </RelativeLayout>

    <!--   7차 : 1,2,3,+  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/border_layout"
        android:layout_weight="1">

        <Button
            android:id="@+id/bt_one"
            android:onClick="numberOnClick"
            android:text="1"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_two"
            android:onClick="numberOnClick"
            android:text="2"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_one"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_three"
            android:onClick="numberOnClick"
            android:text="3"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_toRightOf="@+id/bt_two"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_plus"
            android:onClick="arithmeticOrganOnClick"
            android:text="+"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_three"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>

    </RelativeLayout>

    <!--   8차 : 0, . <- =  -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@drawable/border_layout"
        android:layout_weight="1">

        <Button
            android:id="@+id/bt_zero"
            android:onClick="numberOnClick"
            android:text="0"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" />
        <Button
            android:id="@+id/bt_point"
            android:onClick="pointOnClick"
            android:text="."
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_zero"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>
        <Button
            android:id="@+id/bt_back"
            android:onClick="oneCharClearOnClick"
            android:text="←"
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_point"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>
        <Button
            android:id="@+id/bt_calculator"
            android:onClick="calculatorOnClick"
            android:text="="
            android:textSize="30dp"
            android:layout_width="75dp"
            android:layout_height="45dp"
            android:layout_toRightOf="@+id/bt_back"
            android:layout_centerVertical="true"
            android:background="@drawable/border_calbutton"/>

    </RelativeLayout>

    <!--   9차 : 빈공백 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#00ffffff"
        android:layout_weight="0.5">
    </RelativeLayout>
</LinearLayout>

 

 

4. drawable/border_calbutton.xml

 

 

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 설정된 위젯의 background를 설정
         1. 아래 body설정 부분에서 전체영역이 설정 되면  이 background는 아무 표시가 안난다.
         2. 아래 body설정 부분에서 top,bottom,left,right에 2dp씩 설정 되었기에
            이 2dp만큼  아래 부분에 설정된 모양(rectangle)과 색깔(#f9c7cc)이 보인다.
    -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#f9c7cc" />
        </shape>
    </item>

    <!-- 설정된 위젯의 Body를 설정
         1. top,bottom,left,right 에 2dp 설정
         2. shape : body를 사각형으로 설정
         3. color : body에 color지정
    -->
    <item android:top="2dp" android:bottom="2dp" android:left="2dp" android:right="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#d4d2d2" />
        </shape>
    </item>
</layer-list>

 

 

 

5. drawable/border_layout.xml 

 

 

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 설정된 위젯의 background를 설정
         1. 아래 body설정 부분에서 전체영역이 설정 되면  이 background는 아무 표시가 안난다.
         2. 아래 body설정 부분에서 top, bottom에 2dp씩 설정 되었기에
            이 2dp만큼  아래 부분에 설정된 모양(oval)과 색깔(#6a00ff)이 보인다.
    -->
    <item>
        <shape android:shape="oval">
            <solid android:color="#6a00ff" />
        </shape>
    </item>

    <!-- 설정된 위젯의 Body를 설정
         1. top, bottom 에 2dp 설정
         2. shape : body를 사각형으로 설정
         3. color : body에 color지정
    -->
    <item android:top="2dp" android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#eeffffff" />
        </shape>
    </item>
</layer-list>

 

 

 

 

6. values/colors.xml

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <drawable name="bg_select">#2196F3</drawable>
    <drawable name="bg">#EEEEEE</drawable>
</resources>

 

 

 

'[Android] - 위젯.소스 > 알고리즘1' 카테고리의 다른 글

사칙연산(Queue단계별로 보기)  (0) 2017.01.08
사칙 연산 알고리즘  (0) 2017.01.02
Posted by 농부지기
,

** 사칙연산(Queue단계별로 보기) **

0. 프로젝트명 : QueueCalculatorStep

 

1. 사칙연산을 Queue에 넣다 빼면서 처리

 

2. 화면 설명

    - 4칙 연산식 : +-*/ 연산자가 포함된 계산식

    - queue1 : 4칙 연산식을 queue에 각 문자열별로 넣은 값

    - queue2 : 4칙 연산을 할 때 곱하기, 나누기를 먼저 하고 남은    더하기, 빼기만 남은 연산식

    - pop : 아래 [pop]버튼을 클릭 시 queue에서 빼낸 하나의 문자열

    - 계산     : 곱셈, 나눗셈 하는 식

    - pop버튼 : queue에서 하나를빼내서 보여줌.

 

3. 소스

    https://github.com/farmerkyh/QueueCalculatorStep

 

4. 화면

   

 

 

4. 버전

    - 안드로이드 스튜디오 : v2.2.3

    - Minimum SDK : API 19:Android 4.4 (Kitkat)

5. 소스목록

    1. MainActivity.java

    2. activity_main.xml

 

6. 소스

 

  1. MainActivity.java

 

 package com.example.farmer.queuecalculatorstep;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.Queue;

public class MainActivity extends AppCompatActivity {
    Queue<String> firstQueue = new LinkedList();
    Queue<String> secondQueue = new LinkedList();

    TextView tv_queue1;
    TextView tv_queue2;
    TextView tv_pop1;
    TextView tv_pop2;
    TextView tv_onecalulator;
    TextView tv_result;

    int stepIdx = -1;
    int seq = 0;
    String sResult;

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

        //public member 생성
        tv_queue1 = (TextView)findViewById(R.id.tv_queue1);
        tv_queue2 = (TextView)findViewById(R.id.tv_queue2);
        tv_pop1 = (TextView)findViewById(R.id.tv_pop1);
        tv_pop2 = (TextView)findViewById(R.id.tv_pop2);
        tv_onecalulator = (TextView)findViewById(R.id.tv_onecalulator);
        tv_result = (TextView)findViewById(R.id.tv_result);

        //Button Listener 연동
        Button btnStep  = (Button)findViewById(R.id.btnStep);
        Button btnClear = (Button)findViewById(R.id.btnClear);
        btnStep.setOnClickListener(calOnclickListener);
        btnClear.setOnClickListener(clearOnclickListener);
    }

    Button.OnClickListener calOnclickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            stepIdx++;
            seq = 0;
            calculatorMain();

            //tv_result.setText(sResult);
        }
    };

    //------------------------------------------------------------------------
    // 사칙연사 시작
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void calculatorMain(){
        firstQueue.clear();
        secondQueue.clear();

        //1. 산술식을 queue에 넣기
        stringParsing();
        tv_queue1.setText(firstQueue.toString());
        if (stepIdx==0) return//step 1

        //2. Queue에 저장 된 값 중  곱셈. 나눗셈 계산
        multiplyDivideCal();

        //3 Queue에 저장 된 값 중  덧셈. 뺄샘 계산
        sResult = addSubtractCal();
        //System.out.println("괄호 최종결과 => " + sResult);
    }

    //------------------------------------------------------------------------
    // 1차. 문자열 Parsing
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Queue stringParsing(){
        String sNumList = ((EditText)findViewById(R.id.et_arithmetic)).getText().toString();
        String sOneNum = ""//하나의 숫자열
        for(int i=0; i<sNumList.length(); i++){
            String oneChar = sNumList.substring(i, i+1);
            if ("+-*/()".indexOf(oneChar) >= 0 ){

                // 3+(3  과 같이   4칙연산자와 괄호가 동시에 존재 하는 경우 때문
                if (!"".equals(sOneNum)) firstQueue.offer(sOneNum);   
                firstQueue.offer(oneChar);
                sOneNum = "";
            }else{
                sOneNum += oneChar;

                if (i+1 == sNumList.length()){
                    firstQueue.offer(sOneNum);
                }
            }
        }
        return firstQueue;
    }

    //------------------------------------------------------------------------
    // 곱셈, 나눗셈 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Queue multiplyDivideCal(){
        String oneChar;
        String sNum1 = "", sNum2 = "", sResult = "";
        String operator = "";
        BigDecimal nResult = new BigDecimal("0");
        while(firstQueue.peek() != null){
            oneChar  = firstQueue.poll().toString();
            seq++;
            if (stepIdx == seq) tv_queue1.setText(firstQueue.toString());  //step
            if (stepIdx == seq) tv_pop1.setText(oneChar);  //step
            if (stepIdx == seq) tv_pop2.setText("");

            if ("+-".indexOf(oneChar) >= 0 ){
                secondQueue.offer(sNum1);
                secondQueue.offer(oneChar);
                sNum1 = "";
            }else if ("*/".indexOf(oneChar) >= 0 ) {
                operator = oneChar;
            }else{
                if ("".equals(sNum1)){
                    sNum1 = oneChar;
                }else if ("".equals(sNum2)) {
                    sNum2 = oneChar;
                    if ("*".equals(operator)) {
                        nResult = (new BigDecimal(sNum1)).multiply(new BigDecimal(sNum2));
                    }else if ("/".equals(operator)) {
                        nResult = (new BigDecimal(sNum1)).divide(new BigDecimal(sNum2), 0, BigDecimal.ROUND_UP);
                    }

                    if (stepIdx == seq) tv_pop2.setText(sNum1 + " " + operator + " " + sNum2);
                    sResult  = String.valueOf(nResult);

                    sNum1    = sResult;
                    sNum2    = "";
                    operator = "";
                }
            }

            if (firstQueue.peek() == null) secondQueue.offer(sNum1);

            if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
        }
        return secondQueue;
    }

    //------------------------------------------------------------------------
    // 덧셈. 뺄샘 계산
    //------------------------------------------------------------------------
    @SuppressWarnings({ "rawtypes" })
    public String addSubtractCal(){
        String operator = "";
        String oneChar  = "";
        //if (secondQueue.peek() == null) return "";
        //System.out.println("secondQueue.poll().toString()=" + secondQueue.toString());
        BigDecimal nResult  = new BigDecimal(secondQueue.poll().toString());
        seq++;
        if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
        if (stepIdx == seq) tv_pop1.setText(nResult.toString());  //step
        if (stepIdx == seq) tv_pop2.setText("");

        while(secondQueue.peek() != null){
            oneChar  = secondQueue.poll().toString();
            seq++;
            if (stepIdx == seq) tv_queue2.setText(secondQueue.toString());  //step
            if (stepIdx == seq) tv_pop1.setText(oneChar);  //step
            if (stepIdx == seq) tv_pop2.setText("");

            if ("+-".indexOf(oneChar) >= 0 ){
                operator = oneChar;
            }else{
                if (stepIdx == seq) tv_pop2.setText(nResult + " " + operator + " " + oneChar);
                if ("+".equals(operator)){
                    nResult = nResult.add(new BigDecimal(oneChar));
                }else if ("-".equals(operator)){
                    nResult = nResult.subtract(new BigDecimal(oneChar));
                }
                operator = "";
            }
        }
        return nResult.toString();
    }

    Button.OnClickListener clearOnclickListener = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            stepIdx = -1;
            seq = 0;
            tv_queue1.setText("");
            tv_queue2.setText("");
            tv_pop1.setText("");
            tv_pop2.setText("");
            tv_onecalulator.setText("");
            tv_result.setText("");

            //Toast toast = Toast(getApplicationContext());
            //toast.setText(sResult);
            //toast.setDuration(Toast.LENGTH_LONG);

            Toast toast = Toast.makeText(getApplicationContext(), sResult, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
            View viewToast = toast.getView();

            //Toast BackgroundColor 변경
            //color표기시 xml에서는 "#ffffff"로 하지만
            //java코드에서는 아래와 같이 rgb로 변환하여 사용해줘야 한다.
            viewToast.setBackgroundColor(Color.rgb(255,0,255));

            //Toast Font Color변경
            TextView tvToast = (TextView)viewToast.findViewById(android.R.id.message);
            tvToast.setTextColor(Color.RED);

            toast.show();

            //Toast.makeText(getApplicationContext(), sResult, Toast.LENGTH_LONG).show();
            tv_result.setText(sResult);
        }
    };
}

 

 

 

  2. activity_main.xml

 

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

    android:id="@+id/activity_keypad"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fde002"
    android:orientation="vertical"
    tools:context="com.example.farmer.queuecalculatorstep.MainActivity">>

    <!--  1차 : 산술식 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#b4b2b7"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_num"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="4칙 연산식"/>

        <EditText
            android:id="@+id/et_arithmetic"
            android:text="16+12/1-2*2"
            android:layout_marginRight="10dp"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:paddingLeft="10dp"
            android:background="#ffffff"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_num" />

    </RelativeLayout>

    <!--  2차 : queue1 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e9e0f7"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_lavel1"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="queue 1"/>

        <TextView
            android:id="@+id/tv_queue1"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_lavel1"
            android:background="#ffffff"
            android:text="queue 1"/>
    </RelativeLayout>

    <!--  3차 : queue2 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e9e0f7"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_lavel2"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="queue 2"/>

        <TextView
            android:id="@+id/tv_queue2"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_lavel2"
            android:background="#ffffff"
            android:text="queue 2"/>
    </RelativeLayout>

    <!--  5차 : pop1 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e3ebf4"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_poplavel1"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="pop"/>

        <TextView
            android:id="@+id/tv_pop1"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_poplavel1"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  5차 : pop2 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#e3ebf4"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_poplavel3"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="계산"/>

        <TextView
            android:id="@+id/tv_pop2"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_poplavel3"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  6차 : 4칙연산 하나 계산 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_onelavel"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="4칙연산"/>

        <TextView
            android:id="@+id/tv_onecalulator"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_onelavel"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  7차 : 최종 계산 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/tv_resultlabel"
            android:padding="10dp"
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:text="결과"/>

        <TextView
            android:id="@+id/tv_result"
            android:padding="10dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_centerInParent="true"
            android:layout_toRightOf="@+id/tv_resultlabel"
            android:background="#ffffff"
            android:text=""/>
    </RelativeLayout>

    <!--  8차 : step -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#dbdee1"
        android:layout_marginTop="5dp"
        android:layout_weight="1">

        <Button
            android:id="@+id/btnStep"
            android:text="POP"
            android:layout_centerHorizontal="true"
            android:layout_width="wrap_content"
            android:paddingRight="20dp"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnClear"
            android:text="Clear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btnStep" />
    </RelativeLayout>

    <!--   9차 : 빈공백 -->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#ffffff"
        android:layout_weight="0.5">
    </RelativeLayout>
</LinearLayout>

 

 

 

Posted by 농부지기
,

** 위젯 Border 입히기 **

 

 

1. 정의

    - 위젯(Layout, TextView, EditBox ...)들에게 Border를 줄 수 있다.

    - Border를 줄때 테두리뿐만 아니라  backgounrd, margin등을 설정할 수 있다.

 

2. 개발방법

    2.1 res/drawable/border.xml 파일 생성

    2.2 activity_main.xml 파일에서 border를 입히고 싶은 위젯에 

         [android:background="@drawable/border_calbutton"]설정하면 됨


3. res/drawable/border.xml 파일

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 설정된 위젯의 background를 설정
1. 아래 body설정 부분에서 전체영역이 설정 되면 이 background는 아무 표시가 안난다.
2. 아래 body설정 부분에서 top, bottom에 2dp씩 설정 되었기에
이 2dp만큼 아래 부분에 설정된 모양(oval)과 색깔(#6a00ff)이 보인다.
-->
<item>
<shape android:shape="oval">
<solid android:color="#6a00ff" />
</shape>
</item>

<!-- 설정된 위젯의 Body를 설정
1. top, bottom 에 2dp 설정
2. shape : body를 사각형으로 설정
3. color : body에 color지정
-->
<item android:top="2dp" android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="#eeffffff" />
</shape>
</item>
</layer-list>

 4. activity_main.xml 파일에서 background를 이용해서 설정

     - RelativeLayout에서도 설정할 수 도있고,  button에도 설정할 수 있다.

 <RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@drawable/border"
android:layout_weight="1">

<Button
android:id="@+id/bt_clear"
android:text="농부지기"
android:layout_marginLeft="30dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="@drawable/border"/>


</RelativeLayout>
Posted by 농부지기
,

** Java에서 TableType으로 Procedure 호출 2 **



1. 테이블

CREATE TYPE [dbo].[INITVALS_MSG] AS TABLE(
    [SDate] [decimal](8, 0) NOT NULL,
    [EDate] [decimal](8, 0) NOT NULL,
    [PlantCode] [nvarchar](10) NOT NULL,
    [LoadType] [nchar](8) NOT NULL,
    [Asset] [bigint] NOT NULL
)



2. Procedure

ALTER PROCEDURE [dbo].[RegisterInitAssets]
    @initmsg INITVALS_MSG ReadOnly
AS
BEGIN
    ...


3. java단에서 호출 예제1

   3.1 vo

public class DBInitialAsset {
    private Integer sDate;
    private Integer eDate;
    private String plantCode;
    private String loadType;
    private Integer asset;

    public DBInitialAsset() {

    }
        ...
}

   3.2 sql procedure 호출 예제1

SQLServerDataTable sourceDataTable = new SQLServerDataTable();   
sourceDataTable.addColumnMetadata("SDate", java.sql.Types.DECIMAL);
sourceDataTable.addColumnMetadata("EDate", java.sql.Types.DECIMAL);
sourceDataTable.addColumnMetadata("PlantCode", java.sql.Types.NVARCHAR);
sourceDataTable.addColumnMetadata("LoadType", java.sql.Types.NCHAR);
sourceDataTable.addColumnMetadata("Asset", java.sql.Types.BIGINT);

// sample data
sourceDataTable.addRow(123, 234, "Plant1", "Type1", 123234);   
sourceDataTable.addRow(456, 789, "Plant2", "Type2", 456789);   

try (CallableStatement cs = conn.prepareCall("{CALL dbo.RegisterInitAssets (?)}")) {
    ((SQLServerCallableStatement) cs).setStructured(1, "dbo.INITVALS_MSG", sourceDataTable);
    boolean resultSetReturned = cs.execute();
    if (resultSetReturned) {
        try (ResultSet rs = cs.getResultSet()) {
            rs.next();
            System.out.println(rs.getInt(1));
        }
    }
}


   3.2 sql procedure 호출 예제2

connection = dataSource.getConnection();
CallableStatement statement = connection.prepareCall("{? = call dbo.RegisterInitAssets(?)}");
statement.registerOutParameter(1, OracleTypes.CURSOR);//you can skip this if procedure won't return anything
statement.setObject(2, new InitvalsMsg()); //I hope you some kind of representation of this table in your project
statement.execute();

ResultSet set = (ResultSet) statement.getObject(1);//skip it too if its not returning anything


'(DB) MS SQL > Procedure (단계별스터디)' 카테고리의 다른 글

MS SQL.PLSQL - 문법  (0) 2017.01.27
MS SQL.PLSQL - 단점  (0) 2017.01.27
MS SQL.PLSQL - 장점  (0) 2017.01.27
MS SQL.PLSQL - 특징  (0) 2017.01.27
Java에서 TableType으로 Procedure 호출 1  (0) 2017.01.06
Posted by 농부지기
,

* Java에서 TableType으로 Procedure 호출 *


- Procedure

CREATE PROCEDURE [dbo].[table_sel]
@tbl INT32Table READONLY
AS
BEGIN
SET NOCOUNT ON;
SELECT value FROM @tbl
END


-아래는 호출이 안되는 script

SqlConnection sqlconn;
System.Data.DataTable tbl = new System.Data.DataTable("INT32Table", "dbo");
tbl.Columns.Add("value", typeof(int));
tbl.Rows.Add(2);
tbl.Rows.Add(3);
tbl.Rows.Add(5);
tbl.Rows.Add(7);
tbl.Rows.Add(11);
using (SqlCommand command = new SqlCommand("table_sel"))
{
    command.Connection = sqlconn;
    command.Parameters.AddWithValue("@tbl", tbl);
    command.CommandType = System.Data.CommandType.StoredProcedure;
    SqlDataReader reader = command.ExecuteReader();

    //do stuff
}


-아래는 될거 같은 script 1

java.sql.connection connection = //driver, url, database, credentials ...

try
{
    PreparedStatement ps =
        connection.prepareStatement("insert into tbl values (?)");
    ps.setInt(1, your 1st int);
    ps.addBatch();
    ps.setInt(1, your 2nd int);
    ps.addBatch();
    ps.setInt(1, your 3rd int);
    ps.addBatch();
    ps.executeBatch();
}
catch (SQLException e)
{
    // err handling goes here
}
finally
{
    // close your resources
}



-아래는 될거 같은 script 2

java.sql.connection connection = //driver, url, database, credentials ...

try
{
    CallableStatement cs =
        connection.prepareCall("{ call table_sel(?) }");
    cs.setInt(1, your int);
    cs.execute();
}
catch (SQLException e)
{
    // err handling goes here
}
finally
{
    // close your ressources
}


'(DB) MS SQL > Procedure (단계별스터디)' 카테고리의 다른 글

MS SQL.PLSQL - 문법  (0) 2017.01.27
MS SQL.PLSQL - 단점  (0) 2017.01.27
MS SQL.PLSQL - 장점  (0) 2017.01.27
MS SQL.PLSQL - 특징  (0) 2017.01.27
Java에서 TableType으로 Procedure 호출 2  (0) 2017.01.06
Posted by 농부지기
,

Gradle을 위한 기본 Groovy 문법


http://blog-joowon.tistory.com/1

http://blog-joowon.tistory.com/2

http://blog-joowon.tistory.com/3

http://blog-joowon.tistory.com/4

http://blog-joowon.tistory.com/5

http://blog-joowon.tistory.com/6

http://blog-joowon.tistory.com/7

Posted by 농부지기
,

* 키보드 보이게 하기

 

   - 한글, 숫자 키보디 임

1. Java단에서 아래 두 줄 추가
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

 

'[Android] - 위젯 > EditText' 카테고리의 다른 글

Android.editText 하단라인 보이기.안보이게 하기  (0) 2017.01.30
Focus 막기. Editting 안되게 하기  (0) 2017.01.02
포커스 주기  (0) 2017.01.02
숫자 관련  (0) 2017.01.01
Posted by 농부지기
,

* marquee  (글씨 흐르기)

 

1. Layout 에서

    <TextView
        android:id="@+id/tv_mqrquee"
        android:text="농부 글씨 흐리기..예전에는 logic으로했는데... "


        android:ellipsize="marquee"
        android:focusable="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:singleLine="true"/>

 

2. 위 Layout과 추가적으로 Java단에서  아래를 해줘야 됨
      ((TextView)findViewById(R.id.tv_mqrquee)).setSelected(true);



Posted by 농부지기
,

* Focus 막기. Editting 안되게 하기

 

1. java단에서 - 첫번째 방법

    editText_name.setFocusableInTouchMode(false);  //결과 box에 edit막기

 

 

2. java단에서 - 두번째 방법

                     - key를 눌러도 EditText 에 값이 안찍힘

                     - 단점 : 하지만 keypad가 보임

    editText_name.setKeyListener(null); 

 

 

'[Android] - 위젯 > EditText' 카테고리의 다른 글

Android.editText 하단라인 보이기.안보이게 하기  (0) 2017.01.30
키보드 보이게 하기  (0) 2017.01.02
포커스 주기  (0) 2017.01.02
숫자 관련  (0) 2017.01.01
Posted by 농부지기
,