본문 바로가기

안드로이드

[안드로이드] #2 주식, 코인 평단가계산기 (주식, 코인 평단가 계산기 + 크롤링 + 바텀네비게이션뷰)

안녕하세요

 

이전 블로그 내용과 이어지는 내용입니다.

혹시 이전 블로그를 아직 보지 못하신 분들은 아래 링크를 클릭해 먼저 봐주세요

https://adc6981.tistory.com/8

 

[안드로이드] #1 바텀네비게이션뷰 (주식, 코인 평단가 계산기 + 크롤링 + 바텀네비게이션뷰)

안녕하세요 이번 시간에는 주식 평단가 계산기를 만들어 볼게요 주식 평단가 계산기만 만드는 것이 아니라 현재 코스피, 코스닥 지수와 네이버 금융 주요 뉴스를 크롤링하는 것을 포스팅하겠습

adc6981.tistory.com

 

이번 시간에는 Frag1에 주식, 코인 평단가 계산하는 것을 해보겠습니다.

 

먼저 화면 구성을 해주겠습니다.

RelativeLayout을 이용해 frag1.xml 만들어 보겠습니다.

RelativeLayout이 생소하신 분들도 있을 겁니다.

하지만 속성만 이해한다면 어렵지 않은 레이아웃입니다.

위에 속성들을 참고해서 저의 fram1.xml을 보시면 이해하기 쉬울겁니다.

frag1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:scrollbarSize="4dp">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/top_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerInParent="true"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity=""
                    android:gravity="center|top"
                    android:text="평단가 계산기"
                    android:textSize="30sp" />
            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/now_rel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/top_name"
                android:background="#FBEA4D"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/now"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="2dp"
                    android:layout_marginRight="3dp"
                    android:text="현재보유"
                    android:textSize="20sp" />

                <EditText
                    android:id="@+id/now_money"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/now"
                    android:layout_marginLeft="2dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginBottom="1dp"
                    android:gravity="end"
                    android:hint="현재 보유 평단가(원)"
                    android:inputType="numberDecimal"
                    android:textSize="20sp" />

                <EditText
                    android:id="@+id/now_quantity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/now_money"
                    android:layout_marginLeft="2dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginBottom="1dp"
                    android:gravity="end"
                    android:hint="보유 수량"
                    android:inputType="numberDecimal"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/now_cal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/now_quantity"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:hint="현재 매입 금액" />


                <TextView
                    android:id="@+id/now_amount"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/now_cal"
                    android:layout_alignParentLeft="true"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="3dp"
                    android:layout_weight="1"
                    android:hint="0"
                    android:textSize="17sp"
                    android:textStyle="bold" />

                <ImageButton
                    android:id="@+id/btn_now_money_reset"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/now_quantity"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="3dp"
                    android:layout_marginRight="6dp"
                    android:background="@drawable/ic_baseline_settings_backup_restore_24"
                    android:backgroundTint="@color/black" />


            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/add_rel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/now_rel"
                android:background="#46AAFA"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/add"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="2dp"
                    android:layout_marginRight="3dp"
                    android:text="추가매수"
                    android:textSize="20sp" />

                <EditText
                    android:id="@+id/add_money"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/add"
                    android:layout_marginLeft="2dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginBottom="1dp"
                    android:gravity="end"
                    android:hint=" 평단가(원)"
                    android:inputType="numberDecimal"
                    android:textSize="20sp" />

                <EditText
                    android:id="@+id/add_quantity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/add_money"
                    android:layout_marginLeft="2dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginBottom="1dp"
                    android:gravity="end"
                    android:hint="추가 수량"
                    android:inputType="numberDecimal"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/add_cal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/add_quantity"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:hint="추가 매입 금액" />


                <TextView
                    android:id="@+id/add_amount"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/add_cal"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:layout_weight="1"
                    android:hint="0"
                    android:textSize="17sp"
                    android:textStyle="bold" />

                <ImageButton
                    android:id="@+id/btn_add_money_reset"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/add_quantity"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="3dp"
                    android:layout_marginRight="6dp"
                    android:background="@drawable/ic_baseline_settings_backup_restore_24"
                    android:backgroundTint="@color/black" />


                <ImageButton
                    android:id="@+id/btn_cal"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_below="@+id/btn_add_money_reset"
                    android:layout_alignParentRight="true"
                    android:layout_gravity="right"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="6dp"
                    android:layout_marginBottom="1dp"
                    android:background="@drawable/ic_baseline_drag_handle_24"
                    android:backgroundTint="@color/black" />

            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/add_rel"
                android:layout_weight="1.1"
                android:background="@color/white"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/output"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="2dp"
                    android:layout_marginRight="3dp"
                    android:text="최종보유"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/final_money"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/output"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:text="최종 평단가"
                    android:textSize="17sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/final_quantity"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/final_money"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:text="최종 수량"
                    android:textSize="17sp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/total_money"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/final_quantity"
                    android:layout_marginLeft="3dp"
                    android:layout_marginTop="1dp"
                    android:layout_marginRight="3dp"
                    android:layout_marginBottom="1dp"
                    android:text="총 매수 금액"
                    android:textSize="17sp"
                    android:textStyle="bold" />

                <ImageButton
                    android:id="@+id/btn_all_reset"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/final_money"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="15dp"
                    android:layout_marginRight="6dp"
                    android:background="@drawable/ic_baseline_settings_backup_restore_24"
                    android:backgroundTint="@color/black" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:layout_below="@id/total_money"
                    android:orientation="vertical"></LinearLayout>
            </RelativeLayout>
        </LinearLayout>
    </ScrollView>



</RelativeLayout>

 

간단히 RelativeLayout을 설명드리겠습니다.

노란색으로 표현된 부분을 봐주세요.

현재보유라는 TextView는 부모 기준 왼쪽, 위에 위치하도록 하였습니다.

android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"

현재 보유 평단가(원) 라는 EditText는 now라는 id를 가진 TextView 아래 오도록 위치하였습니다.

android:layout_below="@+id/now"

이렇게 하나하나 위치를 상대적으로 배치할수있습니다.

 

ScrollView를 추가한 이유는 팝업 모드로 보면서 평단가를 계산하기 위해 추가해주었습니다.

ScrollView가 없으면 팝업모드 화면이 작을 때 아래의 화면이 보이지 않습니다.

 

 

 

화면 구성이 끝났다면 Frag1.java의 코드를 작성해 봅시다.

 

Frag와 MainActivity는 변수 선언하는 방법이 조금 다릅니다.

now_money = view.findViewById(R.id.now_money);

이런 식으로 view.findViewById로 해야 합니다.

 

화면 구성한 변수들을 선언해 줍니다.

private EditText now_money,now_quantity,add_money,add_quantity;
private TextView now_amount,add_amount,final_money,final_quantity,total_money;
private ImageButton btn_now_money_reset,btn_add_money_reset,btn_cal,btn_all_reset;
private double a,b,c,d,e,f,g,h,cal;
now_money = view.findViewById(R.id.now_money);
now_quantity = view.findViewById(R.id.now_quantity);
add_money = view.findViewById(R.id.add_money);
add_quantity = view.findViewById(R.id.add_quantity);

now_amount = view.findViewById(R.id.now_amount);
add_amount = view.findViewById(R.id.add_amount);
final_money = view.findViewById(R.id.final_money);
final_quantity = view.findViewById(R.id.final_quantity);
total_money = view.findViewById(R.id.total_money);

btn_now_money_reset = view.findViewById(R.id.btn_now_money_reset);
btn_add_money_reset = view.findViewById(R.id.btn_add_money_reset);
btn_cal = view.findViewById(R.id.btn_cal);
btn_all_reset = view.findViewById(R.id.btn_all_reset);

Double형 변수의 사용 용도입니다.

e=a*b; // 현재 평단가 * 현재 수량
f=c*d; // 추가 매수 평단 * 추가 매수 수량
g=b+d; // 현재 수량 + 추가 매수 수량
h=e+f; // 현재 매입 금액 + 추가 매입 금액
cal=h/g; // 물타기 한 후 평단가

이런 식으로 변수 선언하는 것을 좋지 않은 방법이라고 합니다. 여러분들은 귀찮더라고 해당 변수가 무엇을 뜻하고 있는지 확인할 수 있도록 변수 이름을 설정해 주세요..ㅠ

 

onCreateView에 edit_change(), btn() 함수를 만들어 주고 아래와 같이 작성해주세요

private void edit_change(){
    now_money.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) { ;
            if(now_money.getText().toString().equals("")){
                a=0;
                now_amount.setText("0");
                return;
            }else{
                if(!now_money.getText().toString().equals(".")){
                    a= Double.parseDouble(now_money.getText().toString());
                    e=a*b;
                    String str_e = (String.format("%.4f", e));
                    now_amount.setText(str_e);
                }else {
                    now_money.setText("");
                }

            }
        }

    });
    now_quantity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(now_quantity.getText().toString().equals("")){
                b=0;
                now_amount.setText("0");
                return;
            }else{
                if(!now_quantity.getText().toString().equals(".")){
                    b= Double.parseDouble(now_quantity.getText().toString());
                    e=a*b;
                    String str_e = (String.format("%.4f", e));
                    now_amount.setText(str_e);
                }else{
                    now_quantity.setText("");
                }
            }
        }
    });
    add_money.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(add_money.getText().toString().equals("")){
                c=0;
                add_amount.setText("0");
                return;
            }else{
                if(!add_money.getText().toString().equals(".")){
                    c= Double.parseDouble(add_money.getText().toString());
                    f=c*d;
                    String str_f = (String.format("%.4f", f));
                    add_amount.setText(str_f);
                }else{
                    add_money.setText("");
                }

            }

        }
    });
    add_quantity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if(add_quantity.getText().toString().equals("")){
                d=0;
                add_amount.setText("0");
                return;
            }else{
                if(!add_quantity.getText().toString().equals(".")){
                    d= Double.parseDouble(add_quantity.getText().toString());
                    f=c*d;
                    String str_f = (String.format("%.4f", f));
                    add_amount.setText(str_f);
                }else{
                    add_quantity.setText("");
                }
            }
        }
    });

}

private void btn() {
    btn_cal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(now_money.getText().toString().equals("")){
                Toast.makeText(getActivity(), "현재 보유 평단가를 적어주세요", Toast.LENGTH_SHORT).show();
                return;
            }
            if(now_quantity.getText().toString().equals("")){
                Toast.makeText(getActivity(), "현재 보유 수량을 적어주세요", Toast.LENGTH_SHORT).show();
                return;
            }
            if(add_money.getText().toString().equals("")){
                Toast.makeText(getActivity(), "추가 매입할 주가를 적어주세요", Toast.LENGTH_SHORT).show();
                return;
            }
            if(add_quantity.getText().toString().equals("")){
                Toast.makeText(getActivity(), "추가 매입할 수량을 적어주세요", Toast.LENGTH_SHORT).show();
                return;
            }
            a= Double.parseDouble(now_money.getText().toString());
            b= Double.parseDouble(now_quantity.getText().toString());
            c= Double.parseDouble(add_money.getText().toString());
            d= Double.parseDouble(add_quantity.getText().toString());
            e=a*b; // 현재 평단가 * 현재 수량
            f=c*d; // 추가 매수 평단 * 추가 매수 수량
            g=b+d; // 현재 수량 + 추가 매수 수량
            h=e+f; // 현재 매입 금액 + 추가 매입 금액
            cal=h/g; // 물타기 한 후 평단가

            final_money.setText("최종 평단가 "+(String.format("%.4f", cal)) + " 원");
            final_quantity.setText("최총 수량 "+(String.format("%.8f", g)) + " 개");
            total_money.setText("총 매수 금액 "+(String.format("%.4f", h))+ " 원");

            String str_cal = String.valueOf(cal);
            Log.e("계산", str_cal);

        }
    });
    btn_now_money_reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            now_money.setText("");
            now_quantity.setText("");
        }
    });
    btn_add_money_reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            add_money.setText("");
            add_quantity.setText("");
        }
    });
    btn_all_reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            now_money.setText("");
            now_quantity.setText("");
            add_money.setText("");
            add_quantity.setText("");
            final_money.setText("최종 평단가 ");
            final_quantity.setText("최종 수량 ");
            total_money.setText("총 매수 금액 ");
        }
    });
}

addTextChangedListener는 EditText의 입력 변화가 일어날 때 이벤트를 처리합니다.

@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
	//입력하기 전
}

@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
	//입력난에 변화가 있을 때
}

@Override
public void afterTextChanged(Editable editable) {
	//입력이 끝났을 때
}

addTextChangedListener 참고해주세요

 

String.format("%.4f", e) 소수점 4번째까지 표시하는 방법입니다.

 

현재 시간이 표시되는 상태바의 색갈이 보라색인 것이 별로여서 하얀색으로 변경했습니다.

res→values→themes.xml 에서 

statusBarColor를

<item name="android:statusBarColor" tools:targetApi="l">@color/white</item>
<item name="android:windowLightStatusBar" tools:targetApi="m">true</item>

이렇게 변경해주세요 

 

 

여기까지 잘 따라오셨다면 정상적으로 출력될 것입니다.

 

다음 시간에는 frag2에 현재 코스피, 코스닥과 현재 주요 뉴스를 크롤링하는 내용을 업로드하겠습니다.

수고하셨습니다!

 

반응형