'안드로이드 앱 만들기'에 해당되는 글 43건

  1. 2020.10.06 Linear Layout (2)
  2. 2020.09.22 Fragment끼리 데이터 전송
  3. 2020.09.21 Card View
  4. 2020.09.20 Frame Layout (뷰 끼리 겹치기)
  5. 2020.09.15 Table Layout
  6. 2020.09.12 Check Box (옵션 선택 버튼)
  7. 2020.09.12 Radio Button (옵션 선택 버튼)
  8. 2020.09.12 뷰페이저 (ViewPager androidx ver)
  9. 2020.09.12 Firebase Recycler View
  10. 2020.09.10 Constraint Layout

weightSum - 뷰의 높이 너비를 비율로 설정할 수 있게 해 줌 (단, orientation이 vertical인 경우 높이만 가능하고, horizontal의 경우 너비만 가능)

 

----------------------------------------

activity_main.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="1"
        android:textSize="20sp"
        android:layout_weight="3">

    </TextView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="2"
        android:layout_weight="3">

    </TextView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="3"
        android:textSize="20sp"
        android:layout_weight="3">

    </TextView>

</LinearLayout>

----------------------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Fragment끼리 데이터 전송  (0) 2020.09.22
Card View  (0) 2020.09.21
Frame Layout (뷰 끼리 겹치기)  (0) 2020.09.20
Table Layout  (0) 2020.09.15
Check Box (옵션 선택 버튼)  (0) 2020.09.12
Posted by khon98
,

Fragment에선 findViewById가 바로 작동이 안됨 findViewById앞에 view를 붙여야 함

 

------------------------

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <FrameLayout
        android:id="@+id/framelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

------------------------

 

 

xml 파일 생성

1. res 폴더 > layout 폴더 우클릭 > File name: fragment_1 >

Root element: androidx.constraintlayout.widget.ConstraintLayout

2. design 탭에서 작업

TextView 생성 > Button 생성

------------------------

fragment_1.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <TextView
        android:id="@+id/tv_frag1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="100dp"
        android:text="프래그먼트 1"
        android:textSize="36sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_move"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="프래그먼트 2로 이동"
        app:layout_constraintEnd_toEndOf="@+id/tv_frag1"
        app:layout_constraintStart_toStartOf="@+id/tv_frag1"
        app:layout_constraintTop_toBottomOf="@+id/tv_frag1" />
</androidx.constraintlayout.widget.ConstraintLayout>

------------------------

 

 

xml 파일 복사 후 붙여넣기

------------------------

fragment_2.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <TextView
        android:id="@+id/tv_frag2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="100dp"
        android:text="프래그먼트 2"
        android:textSize="36sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_move"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="프래그먼트 1로 이동"
        app:layout_constraintEnd_toEndOf="@+id/tv_frag2"
        app:layout_constraintStart_toStartOf="@+id/tv_frag2"
        app:layout_constraintTop_toBottomOf="@+id/tv_frag2" />
</androidx.constraintlayout.widget.ConstraintLayout>

------------------------

 

 

------------------------

MainActivity.java

package com.example.fragmentbundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment1 fragment1 = new Fragment1();
        transaction.replace(R.id.framelayout, fragment1);
        transaction.commit(); // 저장
    }
}

------------------------

 

 

java 파일 생성

------------------------

Fragment1.java

package com.example.fragmentbundle;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class Fragment1 extends Fragment {

    private View view;
    private TextView tv_frag1;
    private Button btn_move;
    private String result;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_1, container, false);

        tv_frag1 = view.findViewById(R.id.tv_frag1);
        btn_move = view.findViewById(R.id.btn_move);

        if (getArguments() != null) { // null : 빈 값
            result = getArguments().getString("fromFrag2"); // 프래그먼트 1로 부터 setArguments된 데이터를 받아옴
            tv_frag1.setText(result);
        }

        btn_move.setOnClickListener(new View.OnClickListener() { // 프래그먼트 2로 이동
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle(); // 무언가를 담을 준비를 할 수 있는 보따리 or 꾸러미 같은 느낌
                bundle.putString("fromFrag1","khon 프래그먼트 1");
                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                Fragment2 fragment2 = new Fragment2();
                fragment2.setArguments(bundle);
                transaction.replace(R.id.framelayout, fragment2);
                transaction.commit(); // 저장
            }
        });

        return view;
    }


}

------------------------

 

 

java 파일 복사 후 붙여넣기

------------------------

Fragment2.java

package com.example.fragmentbundle;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class Fragment2 extends Fragment {

    private View view;
    private TextView tv_frag2;
    private Button btn_move;
    private String result;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_2, container, false);

        tv_frag2 = view.findViewById(R.id.tv_frag2);
        btn_move = view.findViewById(R.id.btn_move);

        if (getArguments() != null) { // null : 빈 값
            result = getArguments().getString("fromFrag1"); // 프래그먼트 1로 부터 setArguments된 데이터를 받아옴
            tv_frag2.setText(result);
        }

        btn_move.setOnClickListener(new View.OnClickListener() { // 프래그먼트 2로 이동
            @Override
            public void onClick(View view) { // 프래그먼트 1로 이동
                Bundle bundle = new Bundle(); // 무언가를 담을 준비를 할 수 있는 보따리 or 꾸러미 같은 느낌
                bundle.putString("fromFrag2","khon 프래그먼트 2");
                FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                Fragment1 fragment1 = new Fragment1();
                fragment1.setArguments(bundle);
                transaction.replace(R.id.framelayout, fragment1);
                transaction.commit(); // 저장
            }
        });

        return view;
    }


}

'안드로이드 앱 만들기' 카테고리의 다른 글

Linear Layout (2)  (0) 2020.10.06
Card View  (0) 2020.09.21
Frame Layout (뷰 끼리 겹치기)  (0) 2020.09.20
Table Layout  (0) 2020.09.15
Check Box (옵션 선택 버튼)  (0) 2020.09.12
Posted by khon98
,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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:layout_margin="16dp"
    app:cardCornerRadius="20dp"
    app:cardElevation="8dp"
    android:foreground="?android:attr/selectableItemBackground"
    android:focusable="true"
    android:clickable="true"
    tools:context=".MainActivity">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:layout_gravity="center"
            android:textColor="#000"
            android:text="khon 카드뷰"/>

    </LinearLayout>

</androidx.cardview.widget.CardView>

------------------

 

 

------------------

build.gradle (:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.cardview"
        minSdkVersion 28
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.cardview:cardview:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

'안드로이드 앱 만들기' 카테고리의 다른 글

Linear Layout (2)  (0) 2020.10.06
Fragment끼리 데이터 전송  (0) 2020.09.22
Frame Layout (뷰 끼리 겹치기)  (0) 2020.09.20
Table Layout  (0) 2020.09.15
Check Box (옵션 선택 버튼)  (0) 2020.09.12
Posted by khon98
,

Frame Layout - 여러 개의 뷰를 중첩으로 배치하고 그중 하나를 레이아웃의 전면에 표시할 때 사용하는 레이아웃

액자로 생각하면 쉬움, 큰 사진 앞에 작은 사진을 넣는것처럼 생각하면 됨

 

---------------------

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">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#000000"
            android:src="@drawable/ic_launcher_foreground"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="34sp"
            android:text="안녕하세요"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:layout_gravity="bottom"
            android:textSize="48sp"
            android:text="khon"/>


    </FrameLayout>


</LinearLayout>

'안드로이드 앱 만들기' 카테고리의 다른 글

Fragment끼리 데이터 전송  (0) 2020.09.22
Card View  (0) 2020.09.21
Table Layout  (0) 2020.09.15
Check Box (옵션 선택 버튼)  (0) 2020.09.12
Radio Button (옵션 선택 버튼)  (0) 2020.09.12
Posted by khon98
,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="100dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="100dp"
        android:stretchColumns="*"
        android:background="@drawable/table_outside"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside_gray"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:layout_span="2"
                android:text="khon"
                android:textSize="18sp" />
            
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/table_inside"
                android:gravity="center"
                android:text="khon"
                android:textSize="18sp" />

        </TableRow>

    </TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

--------------------------------

 

 

xml파일 생성

--------------------------------

table_outside.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>

    <stroke android:width="3dp"
        android:color="#000000"/>
</shape>

xml 파일 복사

--------------------------------

 

 

xml 파일 붙여넣기 후 이름 변경

--------------------------------

table_inside.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>

    <stroke android:width="1dp"
        android:color="#000000"/>
</shape>

xml 파일 복사

--------------------------------

 

 

xml 파일 붙여넣기 후 이름 변경

--------------------------------

table_inside_gray.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#8A8A8A"/>

    <stroke android:width="1dp"
        android:color="#000000"/>
</shape>

--------------------------------

'안드로이드 앱 만들기' 카테고리의 다른 글

Card View  (0) 2020.09.21
Frame Layout (뷰 끼리 겹치기)  (0) 2020.09.20
Check Box (옵션 선택 버튼)  (0) 2020.09.12
Radio Button (옵션 선택 버튼)  (0) 2020.09.12
뷰페이저 (ViewPager androidx ver)  (0) 2020.09.12
Posted by khon98
,

+= 기존에 자기가 갖고 있던 값에서 추가된 값

 

-------------------

activity_main.xml

Design 탭에서 CheckBox와 Button 활용

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="결과 텍스트"
        android:textSize="36sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn_result" />

    <CheckBox
        android:id="@+id/chk_red"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="빨강"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <CheckBox
        android:id="@+id/chk_blue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="파랑"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chk_red" />

    <CheckBox
        android:id="@+id/chk_green"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="초록"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chk_blue" />

    <Button
        android:id="@+id/btn_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="선택 완료"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chk_green" />

</androidx.constraintlayout.widget.ConstraintLayout>

-------------------

 

 

-------------------

MainActivity.java

package com.example.checkbox;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    private CheckBox chk_red, chk_blue, chk_green;
    private TextView tv_result;
    private Button btn_result;


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

        chk_red = findViewById(R.id.chk_red);
        chk_blue = findViewById(R.id.chk_blue);
        chk_green = findViewById(R.id.chk_green);
        tv_result = findViewById(R.id.tv_result);
        btn_result = findViewById(R.id.btn_result);

        btn_result.setOnClickListener(new View.OnClickListener() { // 결과 버튼을 클릭했을때 액션
            @Override
            public void onClick(View view) {
                String str_result = ""; // String 값 초기화
                if (chk_red.isChecked()) { // 빨강 체크 박스에 체크가 되어 있다면...
                    str_result += chk_red.getText().toString();
                }
                if (chk_blue.isChecked()) { // 파랑 체크 박스에 체크가 되어 있다면...
                    str_result += chk_blue.getText().toString();
                }
                if (chk_green.isChecked()) { // 초록 체크 박스에 체크가 되어 있다면...
                    str_result += chk_green.getText().toString();
                }
                tv_result.setText(str_result); // 체크 박스에 체크 되어있던 값을 String으로 텍스트 뷰에 출력
            }
        });
    }
}

'안드로이드 앱 만들기' 카테고리의 다른 글

Frame Layout (뷰 끼리 겹치기)  (0) 2020.09.20
Table Layout  (0) 2020.09.15
Radio Button (옵션 선택 버튼)  (0) 2020.09.12
뷰페이저 (ViewPager androidx ver)  (0) 2020.09.12
Firebase Recycler View  (0) 2020.09.12
Posted by khon98
,

null - 비어 있는 값

 

(!= null) - null이 아니면 이라는 뜻(! 붙으면 부정문)

 

---------------------

activity_main.xml

Desing 탭에서 RadioGroup, RadioButton, Button 활용

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <RadioGroup
        android:id="@+id/rg_gender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RadioButton
            android:id="@+id/rd_man"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="남자" />

        <RadioButton
            android:id="@+id/rd_woman"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="여자" />
    </RadioGroup>

    <Button
        android:id="@+id/btn_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="결과 버튼"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/rg_gender" />
</androidx.constraintlayout.widget.ConstraintLayout>

---------------------

 

 

---------------------

MainActivity.java

package com.example.radiobutton;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    private RadioGroup rg_gender;
    private RadioButton rd_man, rd_woman;
    private Button btn_result;
    private String str_result;

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

        rg_gender = findViewById(R.id.rg_gender); // 라디오 버튼들을 담고 있는 그룹
        rd_man = findViewById(R.id.rd_man); // 라디오 버튼
        rd_woman = findViewById(R.id.rd_woman); // 라디오 버튼
        btn_result = findViewById(R.id.btn_result); // 결과 값을 출력하라는 신호를 보낼 버튼

        // 라디오 버튼듣의 상태 값의 변경됨을 감지
        rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rd_man) {
                    Toast.makeText(MainActivity.this, "남자 라디오 버튼", Toast.LENGTH_SHORT).show();
                    str_result = rd_man.getText().toString(); // 라디오 버튼의 text 값을 String에 담아줌
                } else if (i == R.id.rd_woman) {
                    Toast.makeText(MainActivity.this, "여자 라디오 버튼", Toast.LENGTH_SHORT).show();
                    str_result = rd_woman.getText().toString(); // 라디오 버튼의 text 값을 String에 담아줌
                }
            }
        });

        btn_result.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (str_result != null) { // str result가 빈 값이 아니라면
                    Toast.makeText(MainActivity.this, str_result, Toast.LENGTH_SHORT).show();
                } else { // str reulst가 빈 값일 경우
                    Toast.makeText(MainActivity.this, "라디오 버튼을 선택해 주세요", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

'안드로이드 앱 만들기' 카테고리의 다른 글

Table Layout  (0) 2020.09.15
Check Box (옵션 선택 버튼)  (0) 2020.09.12
뷰페이저 (ViewPager androidx ver)  (0) 2020.09.12
Firebase Recycler View  (0) 2020.09.12
Constraint Layout  (0) 2020.09.10
Posted by khon98
,

앱이 죽거나 실행이 안될 경우 activity_main.xml에 있는 ViewPager2를 ViewPager로 바꿔주기

 

--------------------------

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Monday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Tuesday" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Wednesday" />
    </com.google.android.material.tabs.TabLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/const_vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tab_layout">

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

--------------------------

 

 

xml 파일 추가

--------------------------

frag_monday.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon1"
        android:textColor="#000000"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

복사

--------------------------

 

 

이름 수정 후 붙여넣기

--------------------------

frag_tuseday.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon2"
        android:textColor="#000000"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

--------------------------

 

 

이름 수정 후 붙여 넣기

--------------------------

frag_wednesday.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon3"
        android:textColor="#000000"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

--------------------------

 

 

--------------------------

MainActivity.java

package com.example.viewpager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    private FragmentPagerAdapter fragmentPagerAdapter;

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

        // ViewPager 세팅
        ViewPager viewPager = findViewById(R.id.viewPager);
        fragmentPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        TabLayout tabLayout = findViewById(R.id.tab_layout);
        viewPager.setAdapter(fragmentPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }
}

--------------------------

 

 

java파일 생성

--------------------------

FragMonday.java

package com.example.viewpager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragMonday extends Fragment {
    private View view;

    public static FragMonday newInstance() {
        FragMonday fragMonday = new FragMonday();
        return fragMonday;
    }

    // Ctrl + o 누르고 onCreateView
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_monday, container, false);

        return view;
    }
}

 

복사

--------------------------

 

 

이름 수정 후 붙여 넣기

--------------------------

FragTuseday.java

package com.example.viewpager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragTuesday extends Fragment {
    private View view;

    public static FragTuesday newInstance() {
        FragTuesday fragTuesday = new FragTuesday();
        return fragTuesday;
    }

    // Ctrl + o 누르고 onCreateView
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_tuseday, container, false);

        return view;
    }
}

--------------------------

 

 

이름 수정 후 붙여넣기

--------------------------

FragWednesday.java

package com.example.viewpager;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class FragWednesday extends Fragment {
    private View view;

    public static FragWednesday newInstance() {
        FragWednesday fragWednesday = new FragWednesday();
        return fragWednesday;
    }

    // Ctrl + o 누르고 onCreateView
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.frag_wednesday, container, false);

        return view;
    }
}

--------------------------

 

 

java 파일 생성

--------------------------

ViewPagerAdapter.java

package com.example.viewpager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {
    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    // FragMent 교체를 보여주는 처리를 구현한 곳
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return FragMonday.newInstance();
            case 1:
                return FragTuesday.newInstance();
            case 2:
                return FragWednesday.newInstance();
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return 3;
    }

    // Ctrl + o, getPageTitle
    // 상단의 탭 레이아웃 인디케이터 쪽에 텍스트를 선언해주는 곳
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Monday";
            case 1:
                return "Tuesday";
            case 2:
                return "Wednesday";
            default:
                return null;
        }
    }
}

--------------------------

 

 

--------------------------

build.gradle (:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.viewpager"
        minSdkVersion 28
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'com.google.android.material:material:1.2.0-alpha01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

'안드로이드 앱 만들기' 카테고리의 다른 글

Check Box (옵션 선택 버튼)  (0) 2020.09.12
Radio Button (옵션 선택 버튼)  (0) 2020.09.12
Firebase Recycler View  (0) 2020.09.12
Constraint Layout  (0) 2020.09.10
VideoView  (0) 2020.09.08
Posted by khon98
,

private Context context; // 선택한 액티비티에 대한 context를 가져올 때 필요

implementation 'com.github.bumptech.glide:glide:4.10.0' // 이미지 로딩을 더 원활하게 해 줄 수 있는 라이브러리

 

MainActivity.java

1. 상단 Tools 탭 클릭

2. Firebase 클릭 > Realtime Database에 Sava and retrieve data 클릭

3. connect to Firebase

4. Add the Realtime Database to your app 클릭

5. Accept Changes

 

파이어 베이스 콘솔

1. 파이어 베이스 콘솔 검색

2. 좌측 개발 탭에서 Realtime Database 클릭

3. 데이터 베이스 만들기 클릭

4. 테스트 모드에서 시작 클릭 > 사용 설정 클릭

5. 생성된 코드에서 + 클릭

6. 이름 탭에서 User 입력 후, + 클릭

7. 생성된 탭에 이름 User_01 입력 후, + 클릭

8. 생성된 탭에 이름 id 값은 khon 입력 후, User_01 탭에 + 클릭

9. 두번째 생성된 탭에 이름 pw 값은 1234 입력 후, User_01 탭에 + 클릭

10. 세번째 생성된 탭에 이름 userName 값은 khon 입력 후, 추가 버튼 클릭

 

데이터 베이스 안에 이미지 주소 넣기

1. 파이어 베이스 콘솔 사이트 좌측에 Storage 클릭

2. 시작하기 > 다음 > 완료

3. Rulse 클릭

4.

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if true;
    }
  }
}

5. 게시 클릭

6. FIles 클릭 > 파일 업로드(이미지 파일 선택 후 업로드) > 업로드된 파일 클릭 > 액세스 토큰 URL 클릭

7. Realtime Database 클릭 > User_01 탭에 + 클릭 > 생성된 탭에 이름 profile 값에 복사된 URL 붙여넣기 > 추가 클릭

 

결과 값 추가

1. Realtime Database에 우측 상단 점 세개 클릭 후, JSON 내보내기 클릭

2. JSON 파일 메모장으로 실행 후 

{
  "User" : {
    "User_01" : {
      "id" : "khon",
      "profile" : "https://firebasestorage.googleapis.com----",
      "pw" : 1234,
      "userName" : "khon"
    }
  }
}

위 코드들을

{
  "User" : {
    "User_01" : {
      "id" : "khon",
      "profile" : "https://firebasestorage.googleapis.com----",
      "pw" : 1234,
      "userName" : "khon"
    },
"User" : {
    "User_02" : {
      "id" : "khon",
      "profile" : "https://firebasestorage.googleapis.com----",
      "pw" : 1234,
      "userName" : "khon"
    },
"User" : {
    "User_03" : {
      "id" : "khon",
      "profile" : "https://firebasestorage.googleapis.com----",
      "pw" : 1234,
      "userName" : "khon"
    },
"User" : {
    "User_04" : {
      "id" : "khon",
      "profile" : "https://firebasestorage.googleapis.com----",
      "pw" : 1234,
      "userName" : "khon"
    }
  }
}

위 코드 처럼 복사, 붙여 넣기 후 저장

3. Realtime Database 우측 상단 점 세개 클릭 후, JSON 가져오기 클릭

4. 찾아보기 > 저장 한 파일 선택 > 가져오기 클릭

 

--------------------------------

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

--------------------------------

 

 

--------------------------------

MainActivity.java

package com.example.firebaselist;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

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;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private ArrayList<User> arrayList;
    private FirebaseDatabase database;
    private DatabaseReference databaseReference;

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

        recyclerView = findViewById(R.id.recyclerview); // 아이디 연결
        recyclerView.setHasFixedSize(true); // 리사이클러뷰 기존성능 강화
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        arrayList = new ArrayList<>(); // User 객체를 담을 Array 리스트 (어댑터 쪽으로)

        database = FirebaseDatabase.getInstance(); // Firebase Database 연동

        databaseReference = database.getReference("User"); // DB 테이블 연결결
        databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // Firebase Database의 데이터를 받아오는 곳
                arrayList.clear(); // 기존 배열 리스트가 존재하지 않게 초기화
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // 반복문으로 데이터 List를 추출
                    User user = snapshot.getValue(User.class); // 만들어졌던 User 객체에 데이터를 담는다
                    arrayList.add(user); // 담은 데이터들을 배열 리스트에 넣고 리사이클러뷰로 보낼 준비
                }
                adapter.notifyDataSetChanged(); // 리스트 저장 및 새로고침
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // 디비를 가져오던 중 에러 발생 시
                Log.e("MainActivity", String.valueOf(databaseError.toException())); // 에러문 출력
            }
        });

        adapter = new CustomAdapter(arrayList, this);
        recyclerView.setAdapter(adapter); // 리사이클러뷰에 어댑터 연결

    }
}

--------------------------------

 

 

xml 파일 생성

--------------------------------

list_item.xml

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

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

        <ImageView
            android:id="@+id/iv_profile"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_margin="5dp"
            android:src="@drawable/ic_launcher_background"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="15dp"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_id"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="아이디"
                android:layout_margin="5dp"/>

            <TextView
                android:id="@+id/tv_pw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="비밀번호"
                android:layout_margin="5dp"/>

            <TextView
                android:id="@+id/tv_userName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="khon"
                android:layout_margin="5dp"/>

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

--------------------------------

 

 

java 파일 생성

--------------------------------

package com.example.firebaselist;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

    private ArrayList<User> arrayList;
    private Context context; // 선택한 액티비티에 대한 context를 가져올때 필요

    // Alt + Ins 키 누르고 Instructor
    public CustomAdapter(ArrayList<User> arrayList, Context context) {
        this.arrayList = arrayList;
        this.context = context;
    }

    @NonNull
    @Override
    // list View가 Adapter에 연결 돼었을때 뷰 홀더를 만들어 냄
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // 뷰 연결 완료
        CustomViewHolder holder = new CustomViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        Glide.with(holder.itemView)
                .load(arrayList.get(position).getProfile())
                .into(holder.iv_profile);
        holder.tv_id.setText(arrayList.get(position).getId());
        holder.tv_pw.setText(String.valueOf(arrayList.get(position).getPw()));
        holder.tv_userName.setText(arrayList.get(position).getUserName());
    }

    @Override
    public int getItemCount() {
        // 삼향 연산자 (if문과 비슷)
        return (arrayList != null ? arrayList.size() : 0);
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_profile;
        TextView tv_id;
        TextView tv_pw;
        TextView tv_userName;

        public CustomViewHolder(@NonNull View itemView) {
            super(itemView);
            this.iv_profile = itemView.findViewById(R.id.iv_profile);
            this.tv_id = itemView.findViewById(R.id.tv_id);
            this.tv_pw = itemView.findViewById(R.id.tv_pw);
            this.tv_userName = itemView.findViewById(R.id.tv_userName);
        }
    }
}

--------------------------------

 

 

java 파일 생성

--------------------------------

User.java

package com.example.firebaselist;

public class User {
    private String profile;
    private String id;
    private int pw;
    private String userName;

    public User(){}

    // Alt + Ins 키 누르고 Getter and Setter 선택, Shift키 누른 상태로 맨 밑에 코드 클릭
    public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getPw() {
        return pw;
    }

    public void setPw(int pw) {
        this.pw = pw;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

--------------------------------

 

 

--------------------------------

build.gradle (:app)

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.example.firebaselist"
        minSdkVersion 28
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'com.github.bumptech.glide:glide:4.10.0' // 이미지 로딩을 더 원활하게 해줄수 있는 라이브러리
    implementation 'com.google.firebase:firebase-database:19.3.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}

'안드로이드 앱 만들기' 카테고리의 다른 글

Radio Button (옵션 선택 버튼)  (0) 2020.09.12
뷰페이저 (ViewPager androidx ver)  (0) 2020.09.12
Constraint Layout  (0) 2020.09.10
VideoView  (0) 2020.09.08
BroadCastReceiver  (0) 2020.09.07
Posted by khon98
,

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="khon"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginTop="32dp"
        android:text="버튼클릭"
        app:layout_constraintEnd_toEndOf="@+id/textView"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="153dp"
        android:layout_height="169dp"
        android:layout_marginStart="129dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="129dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@android:drawable/ic_menu_compass" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="113dp"
        android:layout_marginBottom="88dp"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toStartOf="@+id/button3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="113dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="88dp"
        android:text="Button"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button2"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>

'안드로이드 앱 만들기' 카테고리의 다른 글

뷰페이저 (ViewPager androidx ver)  (0) 2020.09.12
Firebase Recycler View  (0) 2020.09.12
VideoView  (0) 2020.09.08
BroadCastReceiver  (0) 2020.09.07
RelativeLayout (랠러티브레이아웃)  (0) 2020.09.06
Posted by khon98
,