** Rownum 구현하기**

 

1. sql

   SELECT @rnum := @rnum + 1

      FROM (SELECT @rnum := 0) rn

 

2. SELECT @rnum := 0  : from 절에  @rnum 이라는 변수 생성 및 초기화

    @rnum := @rnum + 1 : 컬럼 절에   @rnum 을 add한다.

 

 

3. set구문을 사용하여 rownum

    SET @rnum := 0;

 

    SELECT @rnum := @rnum + 1

         FROM 테이블명;

 

4. FROM절에서 초기화

    SELECT @rnum := @rnum + 1

       FROM (SELECT @rnum := 0) rn

 

5. WHERE절에서 초기화

    SELECT @rnum := @rnum + 1

       FROM 테이블명

    WHERE (@rnum := 0) = 0;    

Posted by 농부지기
,

** 문자열 결합 **

 

 

MySQL 함수중 GROUP_CONCAT과 CONCAT, CONCAT_WS 가 있다.
이 함수를 이용하면 우리가 원하는 결과를 얻을 수 있다.

1. CONCAT


CONCAT는 Field를 하나의 문자열로 묶어주는 함수이다.
다음과 같이 사용할 수 있다.

CONCAT 예제 (Language : sql)
SELECT CONCAT(`IDX`,'|',`NAME`,'|',`EMAIL`) FROM USER_TEST;

 

 


결과는 다음과 같다.

1|지도리|jidori@nnn.com
2|지돌스타|jidolstar@nnn.com
3|방실이|bangsiri@nnn.com
4|설운도|seolundo@nnn.com
5|박주영|juyoung@nnn.com
6|이효리|hyri@nnn.com


2. CONCAT_WS


CONCAT_WS는 CONCAT과 거의 비슷하다. 하지만 구분자를 한번에 지정할 수 있다는 것이 특징이다.

CONCAT_WS 예제 (Language : sql)
SELECT CONCAT_WS('|', `IDX``NAME``EMAIL`) FROM USER_TEST;



결과는 CONCAT과 완전 동일하다.

3. GROUP_CONCAT


이 함수를 이용하면 GROUPING된 Record를 원하는 구분자를 이용해 문자열로 통합할 수 있다.

예시는 다음과 같다.

GROUP_CONCAT 예제 (Language : sql)
SELECT GROUP_CONCAT(NAME SEPARATOR ';') FROM USER_TEST GROUP BY GROUPNUM;


결과는 다음과 같다.

지도리;지돌스타
방실이;설운도;이효리
박주영

단, 이것만 기억하자. group_concat_max_len 시스템 변수에 의해 최대허용길이를 설정할 수 있는데, default값이 1024이다. 만약 1024byte가 넘어가면 GROUP_CONCAT에 의해 붙은 문자열은 잘린다.

예문2) 결과 컬럼 약쪽에 '(single quote 넣기)

SELECT GROUP_CONCAT("'", part_cd, "'" ) AS part_cd_multi

  FROM hanjul.TPartition ;

결과 : '001', '002', '004' 




제대로 사용해보기 


Query문 부터 보자. 

가로행과 세로열을 모두 구분자로 묶기 (Language : sql)
SELECT  GROUP_CONCAT(
    CONCAT_WS('|'`IDX``NAME``EMAIL`) 
    SEPARATOR '@') 
FROM USER_TEST 
GROUP BY GROUPNUM;
 


결과는 다음과 같다. 

1|지도리|jidori@nnn.com;2|지돌스타|jidolstar@nnn.com
3|방실이|bangsiri@nnn.com;4|설운도|seolundo@nnn.com;6|이효리|hyri@nnn.com
5|박주영|juyoung@nnn.com

이 방법을 사용하면 한번의 Query로 처음에 보여준 PHP코드 처럼 할 필요가 없다는 것을 알 수 있을 것이다.

참고사이트

오라클에서 하는 방법 : http://blog.naver.com/xsoft/150017833358
GROUP_CONCAT() 메뉴얼 : http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
CONCAT() 및 CONCAT_WS() 메뉴얼 : http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat

'(DB) MySql > String 함수' 카테고리의 다른 글

MySql - 문자열 변경. Replace  (0) 2017.01.18
MySql - 문자열 찾기.Find  (0) 2017.01.18
Posted by 농부지기
,

** Toast 모양 변경하기 **

 

0. 프로젝트명 : ToastModify

1. Toast컬러 변경 및 layout을 이용한 Toast변경

 

2. 소스

    1. MainActivity.xml              : layout 조회 및 Toast보여주기

    2. drawable/toast.xml        : Toast모양 변경

    3. layout/activity_main.xml : main activity

    4. layout/activity_toast.xml : Toast모양을 변경 할 Layout. Activity. View

 

3. 화면 :

    - Toast의 좌표

       .  메소드 : Toast.setGravity(int gravity, int xOffset, int yOffset)

       .  gravity : Toast의 기본 위치 지정 (TOP, LEFT, CENTER..)

       .  xOffset, yOffset : gravity 기본 위치를 기준으로 x, y 좌표임

       .  예)  toast.setGravity(Gravity.TOP | Gravity.LEFT150, 300);

 

    - [단순 토스트표시] 버튼 클릭 시 Toast

        

 

   - [LAYOUT토스트 표시]버튼  클릭 시 Toast

       . activity_toast.xml layout을 이용해서 생성

       . drawable/toast.xml 파일에 shape, strok, solid, padding, corner, gradient   tag등을 통해서 Toast 모양 변경

       


 

 

  1. MainActivity.xml

 

package com.example.farmer.toastmodify;

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

public class MainActivity extends AppCompatActivity {

    Button button;
    Button button2;

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

        button = (Button) findViewById(R.id.button);
        button2 = (Button) findViewById(R.id.button2);

        button.setOnClickListener(toastOnclickListener);
        button2.setOnClickListener(layoutOnclickListener);
    }

    Button.OnClickListener toastOnclickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //Toast toast = Toast(getApplicationContext());
            //toast.setText(sResult);
            //toast.setDuration(Toast.LENGTH_LONG);

            String notes = "토스트 내용";

            Toast toast = Toast.makeText(getApplicationContext(), notes, Toast.LENGTH_SHORT);

            //Toast 위치 지정.
            //x,y 좌표는  TOP, LEFT 의 위치에서 시작되는 좌표임
            toast.setGravity(Gravity.TOP | Gravity.LEFT150, 300);

            //Toast는 View를 상속받지 않아서 직접View 객체에 대한 속성을 넣을 수 없다.
            //대신 getView()메소드를 통해서 View객체를 받아서 View속성정의 하면 Toast속성에 적용 된다.
            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(), notes, Toast.LENGTH_LONG).show();
        }
    };

    Button.OnClickListener layoutOnclickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //토스트 모양을 정의하고 있는 레이아웃을 인플레이션 한다.
            //기존 토스트 모양을 작성한 toastborder.xml로 인플레이션 한다.
            LayoutInflater inflater = getLayoutInflater();
            View layout = inflater.inflate(R.layout.activity_toast,
                    (ViewGroup)findViewById(R.id.toast_layout_root));

            //레이아웃의 텍스트뷰에 보여줄 문자열을 설정한다.
            TextView text = (TextView)layout.findViewById(R.id.text);
            text.setText("Layout을 이용한 토스트");

            //토스트 객체 만들기
            Toast toast = new Toast(MainActivity.this);

            //토스트가 출력될 위치를 지정
            //x,y 좌표는  CENTER 의 위치에서 시작되는 좌표임
            toast.setGravity(Gravity.CENTER, 0, -200);

            toast.setDuration(Toast.LENGTH_SHORT);

            //토스트에 뷰를 설정
            toast.setView(layout);

            //토스트 부여주기
            toast.show();
        }
    };
}

 

 

 

  2. drawable/toast.xml

 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <!--
      1. stroke    : 테두리 선
      2. solid      : Toast 내부 색 설정
      3. padding : 여백
      4. corners : 모서리 설정
      5. gradient : 경사도. 변화도
    -->
    <stroke
        android:width="4dp"
        android:color="#ff0008"
        android:dashWidth="5dp"
        android:dashGap="2dp"/>

    <solid
        android:color="#ff883300"/>

    <padding
        android:left="20dp"
        android:top="20dp"
        android:right="20dp"
        android:bottom="20dp"/>

    <corners
        android:radius="100dp"/>

    <gradient
        android:startColor="#ffff0000"
        android:endColor="#80ff00ff"
        android:angle="270"/>

</shape>

 

 

 

 

  3. layout/activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.farmer.toastmodify.MainActivity">

    <Button
        android:id="@+id/button"
        android:text="단순 토스트 표시"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:text="Layout 토스트 표시"
        android:layout_width="wrap_content"
        android:layout_toRightOf="@id/button"
        android:layout_height="wrap_content" />

</RelativeLayout>

 

 

 

 

  4. layout/activity_toast.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:orientation="horizontal"
    android:background="#00ffff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:background="@drawable/toast"/>

</LinearLayout>

 

 

 

Posted by 농부지기
,
[ log4j.xml   파일 예제 ]


'Web. 기타 언어 > log4j. slf4j' 카테고리의 다른 글

4. slf4j - 예제  (0) 2018.10.31
1. Log4j 구성 방법  (0) 2017.01.25
2. log4j 기본 설명  (0) 2017.01.12
Posted by 농부지기
,

프로그램작성시 로그를 남기는 목적으로 만든 프레임워크.

기본은 log4j.jar파일이 있고

확장파일로는 jdbcappender.jar와 ojdbc14.zip파일등이 있다.

 

log4j configuration 파일 설정하기

 

root looger설정

log4j.rootLogger=INFO(로그레벨), console, filelog, dblog(형식)

 

로그레벨을 설정하고 뒤에 root appender를 설정한다.  console(화면출력), filelog,dblog

log level은 debug,info,warn,error,fatal로 구성되고 debug제외 모든 로그가 기록된다.

① FATAL : 가장 크리티컬한 에러가 일어 났을 때 사용합니다. 하위

② ERROR : 일반 에러가 일어 났을 때 사용합니다.                    

③ WARN : 에러는 아니지만 주의할 필요가 있을 때 사용합니다. 1,2,3

④ INFO : 일반 정보를 나타낼 때 사용합니다.  1,2,3,4나타냄

⑤ DEBUG : 일반 정보를 상세히 나타낼 때 사용합니다. 최상위 모두1,2,3,4,5를 모두 나타낸다

 

 

그렇지만 예외적으로 선택적 패키지별로 로그를 사용할수 있다. 이것은

# package logging setting
log4j.logger.com.test(패키지명)=FATAL,logfile 이렇게 해주면 된다.

 

layout타입 : patternlayout

%p : debug,info 로그타입

%d : 로그발생시간 (%d{yyyy-MM-dd HH:mm:ss})

%t :로그 쓰레드 이름

%F: 로그 발생 프로그램 파일명(%F{파일명}

%M : 로그 발생메소드명

%r : 프로그램 시작후 로그 발생까지 시간

%m : 로그로 전달된 메세지

%n: 개행

%L 호출 코드 라인

 

참조한거다 다른 분이 올린거..

[%c] [%C] [%d] [%F] [%l] [%L] [%m] [%M] [%n] [%p] [%r] [%t] [%x] [%X]는 다음과 같다

admin.jsp] [org.apache.jsp.admin_jsp] [2011-02-10 11:30:22,21] ADMIN_jsp.java] [org.apache.jsp.test_jsp._jspService(test_jsp.java:64)] [64][fatal!!] [_jspService] [개행] [FATAL] [765567] [http-8080-Processor25] [] []

 

실제적용

먼저 web.xml에 적용

  <context-param>
     <param-name>log4jConfigLocation</param-name>
     <param-value>/WEB-INF/properties/log4j.properties</param-value>
    </context-param>

속성저장log4j.properties파일

 

## 세팅 stdout,rolling 두개의 appender add

log4j.rootLogger=DEBUG,stdout,fout 디폴트 로그 남기기 
## 콘솔에 출력하기위한  stdout생성
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
## Pattern
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# 호출자의 이름과 라인번호기록

log4j.appender.stdout.layout.ConversionPattern=[%d] %c (%F %L) -%m -%n
# roll 파일이름 설정


## 파일에 출력하기위한  fout생성

 

log4j.appender.fout=org.apache.log4j.DailyRollingFileAppender
## 이클립스의 경우에는  이클립스 자체경로C:\myjava\eclipse가 root가 되어버렸다.
log4j.appender.fout.File=logs/log4j.log\t
log4j.appender.fout.ImmediateFlush=true
log4j.appender.fout.Append=true\t
log4j.appender.fout.DatePattern='.'yyyy-MM-dd-HH(매시간마다)-mm(매분마다)
log4j.appender.fout.layout=org.apache.log4j.PatternLayout
log4j.appender.fout.layout.ConversionPattern=[%d] %c (%F %L) -%m -%n

 

실행방법

 

import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;

 

   Logger log=Logger.getLogger(this.getClass());
   log.debug("자료설정"); info fatal등 속성에 따라 나온다.

이런식으로 넣어주면 알아서 로그파일이나 db에 생성해준다.


참조 : http://blog.naver.com/kimura777/110107337809

[출처] log4j|작성자 숲이면서 나무


'Web. 기타 언어 > log4j. slf4j' 카테고리의 다른 글

4. slf4j - 예제  (0) 2018.10.31
1. Log4j 구성 방법  (0) 2017.01.25
3. log4j.xml 파일 예제  (0) 2017.01.12
Posted by 농부지기
,

** ImageView속성중 scaleType 에따른 표시 효과 **

 

 

 

  1. ImageView 설정 예제

 

<ImageView
    android:id="@+id/image1"
    android:layout_width="100dp"
    android:layout_height="400dp"
    android:src="@mipmap/kokonut"
    android:scaleType="centerCrop"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true" />

 

 

 

 

2. 8 가지 Type

         - 주의 할점은 이 속성은 android:src로 이미지를 불러왔을 때 적용되며 

             android:background로 불러오면 이 속성은 적용 되지 않는다.

속성값

java

설명

matrix

setScaleType(ImageView.ScaleType.MATRIX)

원본 크기 그대로 보여줌 (왼쪽 상단 정렬)

Center

setScaleType(ImageView.ScaleType.CENTER)

원본 크기 그대로 보여줌 (가운데정렬)

centerCrop

setScaleType(ImageView.ScaleType.CENTER_CROP)

View 영역에 공백이 있으면 채워서 보여줌(비율유지)

(ImageView 영역은 match_parent(fill_parent)이다)

ImageView 영역에 공백이 있을 경우 비율을 유지하며 이미지를 늘린다.

centerInside

setScaleType(ImageView.ScaleType.CENTER_INSIDE)

View 영역을 벗어나면 맞춰서 보여줌(비율유지)

centerCrop과는 반대로 ImageView 영역을 벗어나면 비율을 유지하며 줄어든다.

fitStart

setScaleType(ImageView.ScaleType.FIT_START)

View 영역에 맞게 보여줌 (왼쪽상단 정렬비율유지)

fitStart centerInside와 같으며 정렬은 왼쪽 위라는 것이 다르다.

fitCenter

setScaleType(ImageView.ScaleType.FIT_CENTER)

View 영역에 맞게 보여줌 (가운데정렬비율유지)

fitCenter centerInside와 같은 기능을 한다.

fitEnd

setScaleType(ImageView.ScaleType.FIT_END)

View 영역에 맞게 보여줌 (왼쪽하단 정렬비율유지)

fitEnd centerInside와 같으며 정렬은 왼쪽 아래인 것이 다르다.

fitXY

setScaleType(ImageView.ScaleType.FIT_XY)

View 영역을 가득 채워서 보여줌(비율유지 안함)

fitXY는 비율에 상관없이 ImageView영역을 가득 채운다.

Posted by 농부지기
,

** Dynamic Layout Create **

 

1. 프로젝트명 : ToggleCustom

2. 정의 : activity_main.xml을 사용하지 않고 java단에서 Layout을 생성하기

3. 화면 :

   

 

4. 안드로이드 버전

     - 스튜디오 : v2.2.3

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

 

5. 소스목록

   1. MainActivity.java 

 

6. 소스

 

  1. MainActivity.java

 

 package com.example.farmer.layoutjavacreate;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

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

        useDynamic();
    }
    //동적으로 Layout및 버튼 생성
    private void useDynamic(){
        //1. Layout 생성
        LinearLayout layoutMain = new LinearLayout(getApplicationContext());
        LinearLayout.LayoutParams paramsLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        layoutMain.setOrientation(LinearLayout.VERTICAL);
        layoutMain.setLayoutParams(paramsLayout);
        //layoutMain.setBackground(Color.parseColor("#ffffff"));

        //2. Button 생성
        Button button01 = new Button(getApplicationContext());
        Button button02 = new Button(getApplicationContext());
        LinearLayout.LayoutParams paramsButton = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        button01.setLayoutParams(paramsButton);
        button02.setLayoutParams(paramsButton);

        layoutMain.addView(button01);
        layoutMain.addView(button02);

        button01.setText("버튼 1");
        button02.setText("버튼 2");

        setContentView(layoutMain);  //layoutMain은 View임
    }
}

 

Posted by 농부지기
,

** ToggleButton(버튼2개로) **

 

 

1. 프로젝트명 : ToggleCustom

2. 버튼 2개를 이용해서 ToggleButton만들기

3. 화면 :

       

 

4. 안드로이드 버전

     - 스튜디오 : v2.2.3

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

 

5. 소스목록

   1. MainActivity.java 
   2. activity_main.java
   3. drawable/selector_btn_left.xml                    : 왼쪽 버튼 선택 시
   4. drawable/selector_btn_right.xml                 : 오른쪽 버튼 선택 시
   5. drawable/selector_buttons_text.xml            : 선택된 버튼
   6. drawable/shape_btn_unselected_left.xml   : 왼쪽 버튼 미 선택 시
   7. drawable/shape_btn_unselected_right.xml : 오른쪽버튼 미 선택 시
   8. values/colors.xml                                       : color
 

6. 소스

 

 1. MainActivity.java 

 

package com.example.farmer.togglecustom;

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

public class MainActivity extends AppCompatActivity {
    Button test1Button;
    Button test2Button;

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

        test1Button = (Button)findViewById(R.id.test1_button);
        test2Button = (Button)findViewById(R.id.test2_button);

        test1Button.setOnClickListener(topButtonsListener);
        test2Button.setOnClickListener(topButtonsListener);
        test1Button.performClick();  //첫번째 버튼을 눌린 효과를 줌
    }

    View.OnClickListener topButtonsListener  = new View.OnClickListener(){
        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.test1_button){
                test1Button.setSelected(true);
                test2Button.setSelected(false);
            }
            else{
                test1Button.setSelected(false);
                test2Button.setSelected(true);
            }
        }
    };


}

 

 

  2. activity_main.java

 

<?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.farmer.togglecustom.MainActivity">

        <Button
            android:id="@+id/test1_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_weight="1"
            android:textColor="@color/selector_buttons_text"
            android:background="@drawable/selector_btn_left"
            android:text="Test 1"/>

        <Button
            android:id="@+id/test2_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:textColor="@color/selector_buttons_text"
            android:background="@drawable/selector_btn_right"
            android:text="Test 2"
            android:layout_weight="1"/>


</LinearLayout>

 

 

 

  3. drawable/selector_btn_left.xml

 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@color/gen_app_color" android:state_pressed="true" />
    <item android:drawable="@color/gen_app_color" android:state_selected="true" />
    <item android:drawable="@drawable/shape_btn_unselected_left" />
</selector>

 

 

 

  4. drawable/selector_btn_right.xml

 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@color/gen_app_color" android:state_pressed="true" />
    <item android:drawable="@color/gen_app_color" android:state_selected="true" />
    <item android:drawable="@drawable/shape_btn_unselected_right" />
</selector>

 

 

 

  5. drawable/selector_buttons_text.xml

 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="@android:color/white" />
    <item android:state_pressed="true" android:color="@android:color/white" />
    <item android:color="@color/gen_app_color"/>
</selector>

 

 

 

  6. drawable/shape_btn_unselected_left.xml

 

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white"/>
            <stroke android:width="5px" android:color="#337799" />
        </shape>
    </item>
    <item android:left="5dp"
        android:top="2dp"
        android:bottom="2dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFFFF" />
        </shape>
    </item>
</layer-list>

  

 

  7. drawable/shape_btn_unselected_right.xml

 

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

    <color name="gen_app_color">#40ffe6</color>
    <color name="selector_buttons_text">#ff404a</color>
</resources>

 

 

  8. 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>

    <color name="gen_app_color">#40ffe6</color>
    <color name="selector_buttons_text">#ff404a</color>
</resources>

 

 

Posted by 농부지기
,

** 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 농부지기
,