반응형

파이어 베이스 주소 : https://firebase.google.com/?hl=ko

 

Firebase

Firebase는 고품질 앱을 빠르게 개발하고 비즈니스를 성장시키는 데 도움이 되는 Google의 모바일 플랫폼입니다.

firebase.google.com

1. 우선 firebase 프로젝트를 만든다. (굳이 처음에 안만들어도 안드로이드 스튜디오에서 만들 수 있음.)

프로젝트 제목은 20200523으로 설정하였다.

2. 여기서 실시간 데이터 베이스를 선택한다.

3. 실시간 데이터베이스를 들어가면 이런 화면이 뜨는데 여기서 데이터 옆에 규칙을 눌러준다.

4. 규칙에 들어가면 이런 화면이 뜨는데 데이터베이스에 저장된 내용을 읽고 쓰기 위해서 readwritetrue로 바꿔준다.(기본 상태는 false이다.)

5. 안드로이드 스튜디오에서 새로운 프로젝트를 만든뒤에 Tools에 firebase를 눌러준다.

6. 파이어베이스를 누르면 이런 화면이 나오게 되는데 여기서 Realtime Database를 눌러준다.

7. 새로운 프로젝트를 만들거나 이미 만들어놓은 프로젝트를 선택한 뒤 Connect to Firebase를 누른다.

 그러면 이렇게 로그인 화면이 나오게 되고 파이어베이스를 사용할 때 쓰는 구글 아이디로 로그인하면 된다.

이런 화면이 나오게 되는데

허용을 누르면 이렇게 완료라는 화면이 나온다.

밑에는 파이어베이스와 앱을 연결해주는 코드 

   1) MainActivitay.java

package com.example.dbexam;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private EditText editText;
    private Button button;

    DatabaseReference mRoootRef = FirebaseDatabase.getInstance().getReference();
    // DatabaseReference 는 데이터베이스에서 데이터를 읽고 쓰려면 꼭 필요
    DatabaseReference conditionRdf = mRoootRef.child("text");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 데이터의 변화를 알기 위해
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
    }
    protected void onStart(){
        super.onStart();

        conditionRdf.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // 데이터 값이 변했을 때마다 작동, text 안에 받아온 데이터 문자열을 넣어줌
                String text = dataSnapshot.getValue(String.class);
                textView.setText(text);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // 에러가 날 때 작동
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conditionRdf.setValue(editText.getText().toString());
            }
        });
    }


}

   2) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:textSize="30dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical|center_horizontal"
        android:text="TextView" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="TEXT를 입력하세요"
            android:inputType="text"
            />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send" />
    </LinearLayout>
</LinearLayout>

안드로이드 스튜디오를 사용하기 전에는 앱인벤터로 firebase와 연결했는데 앱인벤터가 알다시피 제약이 많기에 불편했는데 안드로이드 스튜디오는 너무 쉽고 빠르게 잘 연결 되어서 좋았다.

반응형
반응형

(1) MainActivity.java

package com.example.mutitouch;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MultiTouchView(this, null));
    }
}

(2) MultTouchView.java

package com.example.mutitouch;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.jar.Attributes;

public class MultiTouchView extends View {
    private static final int SIZE = 60;
    final int MAX_POINTS = 10;
    float[] x = new float[MAX_POINTS];
    float[] y = new float[MAX_POINTS];
    boolean[] touching = new boolean[MAX_POINTS];

    private Paint mPaint;

    public MultiTouchView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint((Paint.ANTI_ALIAS_FLAG));
        mPaint.setColor(Color.BLUE);
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int index = event.getActionIndex();
        int id = event.getPointerId(index);
        int action = event.getActionMasked();
        switch (action){
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
                x[id] = (int) event.getX(index);
                y[id] = (int) event.getY(index);
                touching[id] = true;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_CANCEL:
                    touching[id] = false;
                break;
        }
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for(int i = 0; i < MAX_POINTS; i++){
            if(touching[i]){
                canvas.drawCircle(x[i], y[i], SIZE, mPaint);
            }
        }
    }
}

반응형
반응형

xml 파일은 필요하지 않음.

(1)MainActivity.java

package com.example.touchevent;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    protected class MyView extends View {
        int x = 100, y = 100;
        String str;
        public MyView(Context context) {
            super(context);
            setBackgroundColor(Color.YELLOW);
        }
        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = new Paint(); // paint.setColor(Color.BLUE);
            paint.setColor(Color.rgb(0,0,255));
            canvas.drawCircle(x, y, 50, paint);
            paint.setTextSize(50);
            canvas.drawText("액션의 종류: " + str, 0, 100, paint);
        }
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            x = (int) event.getX();
            y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP)
                str = "ACTION_UP";
            if (event.getAction() == MotionEvent.ACTION_DOWN)
                str = "ACTION_DOWN";
            if (event.getAction() == MotionEvent.ACTION_MOVE)
                str = "ACTION_MOVE";
            invalidate();
            return true;
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView myView = new MyView(this);
        setContentView(myView);
    }
}

(2) 실행화면

반응형
반응형

배달앱이나 여러 쇼핑사이트들에서 흔히 볼 수 있는 평점 다는 기능을 (별점) ratingbar로 구현 해보았다.

(1) MainActivity.java

package com.example.ratingapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    TextView textView2;
    RatingBar ratingBar;
    String str;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ratingBar = findViewById(R.id.ratingBar);
        textView2 = findViewById(R.id.textView2);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                Toast.makeText(getApplicationContext(),"New Rating: "+ rating, Toast.LENGTH_SHORT).show();
                str = String.valueOf(rating);
                str = Float.toString(rating);
                textView2.setText(str);
            }
        });
    }
}

결과 텍스트의 rating에서 얻은 값을 넣고 싶어서 float형을 string형으로 바꾸었다. 

-> float 형을 string으로 바꾸는 법

str = String.valueOf(rating);
str = Float.toString(rating);

(2) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:backgroundTint="#C11515"
        android:numStars="5"
        android:stepSize="1.0" />

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

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="평점은: "
            android:textSize="20dp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:hint="결과"
            android:textSize="20dp" />
    </LinearLayout>

</LinearLayout>

평점 어플

 

반응형
반응형

RadioButton을 사용하여 성별을 체크하는 앱 만들기 

먼저 라디오 그룹 밑에 라디오 버튼 3개를 넣어준다. (레이아웃은 LinearLayout으로 한다. 사실 이 레이아웃으로 왠만한 레이아웃 만들기 다 가능)

 

1. activity_main.xml

이제 버튼이나 텍스트 그리고 배경에 색을 입혀주었다.

색 참고 주소 https://color.adobe.com/ko/create

 

https://color.adobe.com/ko/create

 

color.adobe.com

여기에 들어가서 색을 조합한 다음 복사해서 붙여준다.

android:textColor="#000000"
android:background="#E6D7BE"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FDFBDE"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="당신은 ?"
        android:textColor="#000000"
        android:textSize="20dp"
        android:background="#E6D7BE"
        android:padding="16dp"
        android:gravity="center"
        android:singleLine="true"
        android:textStyle="bold" />

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radio_men"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="남자" />

        <RadioButton
            android:id="@+id/radio_women"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="여자" />

        <RadioButton
            android:id="@+id/radio_robot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="로봇" />

    </RadioGroup>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#E8CA90"
        android:textSize="17dp"
        android:textStyle="bold"
        android:text="확인" />

</LinearLayout>

이 상태에서 저 View Options(눈모양 저거 말하는 거임) 누르고 show Layout Decorations를 누르면 

이렇게 된다.

2. MainActivity.java

package com.example.myapplicationtest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    RadioButton radio_men, radio_women, radio_robot;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        radio_men = findViewById(R.id.radio_men);
        radio_men.setChecked(true);
        radio_men.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_women.isChecked())
                    textView.setText("여자가 체크되었습니다.");
                else
                    textView.setText("로봇이 체크되었습니다.");
            }
        });
        radio_women = findViewById(R.id.radio_women);
        radio_women.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_men.isChecked())
                    textView.setText("남자가 체크되었습니다.");
                else
                    textView.setText("로봇이 체크되었습니다.");
            }
        });
        radio_robot = findViewById(R.id.radio_robot);
        radio_robot.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(radio_robot.isChecked())
                    textView.setText("로봇이 체크되었습니다.");
                else
                    textView.setText("여자가 체크되었습니다.");

            }
        });
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                String str;
                if(radio_men.isChecked()) {
                    str = "남자";
                }
                else if(radio_women.isChecked()){
                    str = "여자";
                }
                else{
                    str = "로봇";
        }
            Toast.makeText(getApplicationContext(),"당신은" + str,Toast.LENGTH_SHORT).show();
            }
        });

    }
}

 

3. 실행화면 

반응형
반응형

버튼을 누르면 다른 화면으로 넘어감.

 

MainActivity.java

package com.example.intentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
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 {
    Button btn_move;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_move = findViewById(R.id.btn_move);
        editText = findViewById(R.id.editText);
        btn_move.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = editText.getText().toString();
                editText.setText("clear");
                Intent intent = new Intent(MainActivity.this, SubActivity.class);
                intent.putExtra("str",str);
                startActivity(intent);
            }
        });
    }

}

이동이라는 버튼을 누르면 "글자를 입력하세요" 창이 clear로 변하고 다음 창으로 thanks를 가지고 넘어감. 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:hint = "글자를 입력하세요" />

    <Button
        android:id="@+id/btn_move"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="이동" />

</LinearLayout>

"글자를 입력하세요" 창은 EditText, weight를 1로해서 길게 만듬

이동이라는 버튼은 wrap_content로 글씨 길이에 맞게 설정

 

1번째 화면

SubActivity.java

package com.example.intentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SubActivity extends AppCompatActivity {
    private TextView textSub;
    private Button btn_back;

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

        textSub = findViewById(R.id.textSub);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 액티비티 종료 메인화면으로
            }
        });
        Intent intent = getIntent();
        String str = intent.getStringExtra("str");
        textSub.setText(str);
    }
}

activity_sub.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SubActivity" >

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="메인으로 돌아가기" />

    <TextView
        android:id="@+id/textSub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical|center_horizontal"
        android:text="TextView" />
</LinearLayout>
public void onClick(View v) {
	finish(); // 액티비티 종료 메인화면으로
}

2번째 이동한 화면

토스트메세지 

Toast.makeText(getApplicationContext(),"버튼이 눌렸습니다.",Toast.LENGTH_LONG).show();

반응형

+ Recent posts