3장. 위젯

2023. 11. 7. 21:21·안드로이드/연습 코드

1. GradientDrawable, StateListDrawable

1-1. back_drawable.xml

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

    <gradient
        android:startColor="#7288DB"
        android:centerColor="#3250B4"
        android:endColor="#254095"
        android:angle="90"
        android:centerY="0.5"
        />

    <corners android:radius="2dp" />
</shape>

 

1-2. finger_drawable.xml (여기에서 클릭을 감지)

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

    <item android:state_pressed="true" android:drawable="@drawable/finger_pressed" />
    <item android:drawable="@drawable/finger" />
</selector>

 

1-3. 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"
    android:background="@drawable/back_drawable"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/finger2_drawable"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/rect_drawable"
        android:text="Button"
        app:backgroundTint="#00000000"
        app:backgroundTintMode="add"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/border_drawable"
        android:text="Button"
        app:backgroundTint="#00000000"
        app:backgroundTintMode="add"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

 


2. Event (GesterDetetor 사용)

2-1. 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">

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_bright" />

    <View
        android:id="@+id/view2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@android:color/holo_orange_light" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

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

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

 

2-2. MainActivity.java

package org.techtown.sampleevent;

import android.os.Bundle;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    GestureDetector detector;

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

        textView = findViewById(R.id.textView);

        View view = findViewById(R.id.view);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int action = motionEvent.getAction();
                float curX = motionEvent.getX();
                float curY = motionEvent.getY();

                if (action == MotionEvent.ACTION_DOWN) {
                    println("손가락 눌림 : " + curX + ", " + curY);
                } else if (action == MotionEvent.ACTION_MOVE) {
                    println("손가락 움직임 : " + curX + ", " + curY);
                } else if (action == MotionEvent.ACTION_UP) {
                    println("손가락 뗌 : " + curX + ", " + curY);
                }

                return true;
            }
        });

        detector = new GestureDetector(this, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent motionEvent) {
                println("onDown() 호출됨.");
                return true;
            }

            @Override
            public void onShowPress(MotionEvent motionEvent) {
                println("onShowPress() 호출됨.");
            }

            @Override
            public boolean onSingleTapUp(MotionEvent motionEvent) {
                println("onSingleTapUp() 호출됨.");
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
                println("onScroll() 호출됨 : " + v + ", " + v1);
                return true;
            }

            @Override
            public void onLongPress(MotionEvent motionEvent) {
                println("onLongPress() 호출됨.");
            }

            @Override
            public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
                println("onFling() 호출됨 : " + v + ", " + v1);
                return true;
            }
        });

        View view2 = findViewById(R.id.view2);
        view2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                detector.onTouchEvent(motionEvent);
                return true;
            }
        });


    }

    public void println(String data) {
        textView.append(data + "\n");
    }
    
    @Override
    public void onBackPressed() {
        Toast.makeText(this, "시스템 BACK 버튼 터치", Toast.LENGTH_LONG).show();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Toast.makeText(this, "시스템 [BACK] 버튼이 눌렸습니다.", Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }

}

 

 


3. 라디오박스와 Complete 버튼 구현

3-1. 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">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:text="What is your favorite pet?"
        android:textSize="24sp"
        android:visibility="visible" />

    <RadioGroup
        android:id="@+id/radiogroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:visibility="visible">

        <!-- 라디오 버튼 추가 -->
        <RadioButton
            android:id="@+id/rbtn1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="dog" />

        <RadioButton
            android:id="@+id/rbtn2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="cat" />

        <RadioButton
            android:id="@+id/rbtn3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="20dp"
            android:text="rabbit" />
    </RadioGroup>

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:text="Complete"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:visibility="invisible"
        <!-- 여기에 src attribute를 assign -->
        app:srcCompat="@drawable/dog" />
</LinearLayout>

 

3-2. MainActivity.java

package com.example.petapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView text;
    RadioGroup radioGroup;
    RadioButton radioButton1,radioButton2,radioButton3;
    Button button;
    ImageView image;

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

        text = findViewById(R.id.text);
        radioGroup = findViewById(R.id.radiogroup);
        radioButton1 = findViewById(R.id.rbtn1);
        radioButton2 = findViewById(R.id.rbtn2);
        radioButton3 = findViewById(R.id.rbtn3);
        button = findViewById(R.id.btn);
        image = findViewById(R.id.image);

        // radioBox에 체크하는 것으로 사진이 교체
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                // < your code >
                if (i == R.id.rbtn1) {
                    image.setImageResource(R.drawable.dog);
                } else if (i == R.id.rbtn2) {
                    image.setImageResource(R.drawable.cat);
                } else {
                    image.setImageResource(R.drawable.rabbit);
                }
            }
        });

        // 버튼을 클릭하면 이미지가 보인다
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                image.setVisibility(View.VISIBLE);
            }
        });
    }
}

 

'안드로이드 > 연습 코드' 카테고리의 다른 글

6장. 서비스와 브로드캐스트 리시버  (0) 2023.11.07
5장. Fragment  (0) 2023.11.07
4장. Activity와 Intent  (0) 2023.11.07
2장. 뷰와 레이아웃  (0) 2023.11.07
1장. URL 버튼 만들기  (0) 2023.11.07
'안드로이드/연습 코드' 카테고리의 다른 글
  • 5장. Fragment
  • 4장. Activity와 Intent
  • 2장. 뷰와 레이아웃
  • 1장. URL 버튼 만들기
달거달거
달거달거
개발자를 꿈꿉니다
  • 달거달거
    SWEE IT
    달거달거
  • 전체
    오늘
    어제
    • 분류 전체보기 (288)
      • 개발 환경 (5)
        • VSCode (1)
        • 파이썬 (Anaconda) (1)
        • Git (1)
        • Flutter (0)
        • Kotlin (1)
      • Spring (5)
        • 스프링 부트와 JPA 실무 완전 정복 로드맵 (2)
        • 스프링 부트와 AWS로 구현하는 웹 서비스 (1)
        • 채쌤의 스프링 부트 프로젝트 (1)
      • 알고리즘과 코딩 테스트 (16)
        • 파이썬 문법 (2)
        • 백준 25단계 (10)
        • 프로그래머스 코딩 테스트 고득점 Kit (1)
        • 코틀린 문법 (1)
      • 요리 (236)
      • 데이터베이스 (2)
        • MySQL (2)
      • 안드로이드 (11)
        • 연습 코드 (6)
        • 도서 내용 정리 (4)
      • Dart와 Flutter (5)
        • 도서 내용 정리 (4)
        • Flutter 위젯 정리 (1)
        • 15개 프로젝트 (2)
      • 피그마 (0)
        • 도서 내용 정리 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    머신러닝
    코틀린
    Flutter
    피그마
    자취요리
    AWS
    c++
    파이썬
    docker
    데이터베이스
    C
    백준
    코딩 테스트
    안드로이드
    문법
    vscode
    티스토리챌린지
    프로그래머스
    아나콘다
    git
    node.js
    JPA
    mysql
    오블완
    알고리즘
    spring
    주석
    DART
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
달거달거
3장. 위젯
상단으로

티스토리툴바