안드로이드

1 2 3 4 5

테두리 설정하기


drawable - New - Drawable Resource File 클릭.

 

Root element에 layer-list 입력하고, 원하는 파일명 작성 후 OK.

 

up_down_border.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="2dp"
        android:left="-3dp"
        android:right="-3dp"
        android:bottom="2dp">
        <shape android:shape="rectangle" >
            <stroke
                android:width="2dp"			// 테두리 두께
                android:color="#aaa" />		// 테두리색

            <solid android:color="#FFF" />	// 배경색
        </shape>
    </item>
</layer-list>

top, left, right, bottom에 있는 값들은 선의 위치입니다. - 값을 이용해 원하는 테두리만 표시되도록 설정이 가능합니다.

 

android:background="@drawable/up_down_border"

완성한 xml파일은 background에서 사용하시면 됩니다.



 

ConstraintLayout Widget 에러

This view is not constrained vertically...


 

This view is not constrained vertically: at runtime it will jump to the top unless you add a vertical constraint 에러가 발생하는 경우

Layout으로 ConstraintLayout을 사용하고 있을 겁니다.

 

이 경우에 Design이나 Code에서 제약(Constraint)를 설정해줘야 합니다.

 

Constraint를 설정해주시면 에러가 사라집니다~



android:windowSoftInputMode="adjustResize"


 

Manifest.xml파일 내부에 activity태그 안에 android:windowSoftInputMode="adjustResize"를 만들어 작성해주시면 됩니다.

 

adjustResize는 키보드가 올라올 때 EditText를 resize해서 키보드에 가려지는 UI가 없도록 만들어 줍니다.



코드가 바로 실행되지 않고 약간의 시간이 필요한 경우 Handler를 이용해서 딜레이를 설정할 수 있습니다.

 

new Handler().postDelayed(new Runnable()
{
	@Override
	public void run()
	{
		// 딜레이가 끝난 후 실행할 코드 작성.
	}
}, 1000);// 딜레이 시간 설정. (1초 = 1000)

 



위와 같은 에러가 발생할 경우

build.gradle(module:app)에 코드를 추가시켜주면 됩니다.

defaultConfig{
	vectorDrawables.useSupportLibrary = true
}​

'안드로이드 > Android 에러' 카테고리의 다른 글

[Android] ConstraintLayout Widget 에러  (0) 2020.08.31

하단네비게이션

 

 

1. gradle 추가

2. activity_main.xml

3. menu 폴더 생성

4. bottom_menu.xml

5. java파일 및 xml 생성

6. MainActivity


1. gradle 추가

implementation 'com.android.support:design:28.0.0'

 

build.gradle에 implementation 추가시켜줍니다.

버전이 맞지 않으면 에러가 발생할 수 있으므로 버전을 맞춰주세요.

 

2. 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/main_frame"
        android:layout_width="match_parent"
        android:layout_height="659dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavi"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconTint="#000"
        app:itemTextColor="#000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/bottom_menu"
        tools:layout_editor_absoluteX="8dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

3. menu 폴더 생성

res - New - Android Resource Directory에서 Resource type을 menu로 선택 후 생성.

 

4. bottom_menu.xml 생성

menu 폴더에 bottom_menu.xml 생성 후 메뉴 추가.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/show"
        android:enabled="true"
        android:icon="@drawable/ic_import_contacts_black_24dp"
        android:title="보기"/>

    <item
        android:id="@+id/write"
        android:enabled="true"
        android:icon="@drawable/ic_create_black_24dp"
        android:title="쓰기"/>

    <item
        android:id="@+id/info"
        android:enabled="true"
        android:icon="@drawable/ic_info_outline_black_24dp"
        android:title="정보"/>
</menu>

 

5. java파일 및 xml 생성

각각의 메뉴마다 연결시킬 파일 만들기

 

- Fragment1.java

public class Fragment1 extends Fragment {

    private View view;

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



        return view;
    }
}

- fragment1.xml

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="30sp"
        android:text="fragment1"/>

</LinearLayout>

위와 같이 2와 3에 해당하는 java파일 & xml 파일 추가 생성~!

 

 

6. MainActivity

public class MainActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView; // 바텀네비게이션 뷰
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Fragment1 fragment1;
    private Fragment2 fragment2;
    private Fragment3 fragment3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavi);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){

                    case R.id.show:
                        setFrag(0);
                        break;
                    case R.id.write:
                        setFrag(1);
                        break;
                    case R.id.info:
                        setFrag(2);
                        break;
                }
                return true;
            }
        });

        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();

        setFrag(0); // 첫화면 설정
    }

    // 프래그먼트 교체가 일어나는 메서드
    private void setFrag(int n){

        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();

        switch (n){
            case 0:
                transaction.replace(R.id.main_frame, fragment1);
                transaction.commit();
                break;
            case 1:
                transaction.replace(R.id.main_frame, fragment2);
                transaction.commit();
                break;
            case 2:
                transaction.replace(R.id.main_frame, fragment3);
                transaction.commit();
                break;
        }
    }
}


1. gradle 추가

2. AndroidManifest 추가

3. xml 작성

4. java 작성

 


https://sseong66.tistory.com/47

 

[Android] 구글맵 API 키 발급

구글맵 API 키 발급 받기 https://console.cloud.google.com/projectselector2/apis/dashboard Google Cloud Platform 하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요. a..

sseong66.tistory.com

시작하기 전에 API 키를 발급받지 않았으면 위 링크로 이동해 API 키 발급을 먼저 진행해주세요.

 

 

1. gradle 추가

dependencies {

	...

    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
}

dependencies에 구글맵에 필요한 2가지 종속성을 추가시킨 후 Sync Now 클릭.

 

 

2. AndroidManifest 추가

<manifest>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        
        ...

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCkR6r2uJz2dK5J3pP2Gj9Pq9iv-GfXu7o"/>

    </application>

</manifest>

구글맵에 필요한 uses-permission 2개와 meta-data를 추가시켜줍니다.

meta-data의 value에는 발급받은 API키를 입력하면 됩니다.

 

 

3. xml 작성

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/gMap"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	class="com.google.android.gms.maps.SupportMapFragment"/>

xml에 구글맵을 표시할 fragment를 추가해줍니다.

class를 작성하지 않으면 앱이 정상 작동이 되지 않을 수 있습니다! (이틀 날려먹음 T^T)

 

4. java 작성

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    GoogleMap map;

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

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.gMap);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        map = googleMap;

        LatLng location = new LatLng(37.239912, 131.869296);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.title("독도");
        markerOptions.snippet("Dokdo is korean territory");
        markerOptions.position(location);
        map.addMarker(markerOptions);

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(location,16));
    }
}

아무것도 작성하지 않아도 실행이 가능합니다.

 

위와 같이 작성하시면 지도에 마커를 생성할 수 있습니다.



구글맵 API 키 발급 받기


 

https://console.cloud.google.com/projectselector2/apis/dashboard

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

구글 클라우드 플랫폼에 접속해서 API키를 발급받아야 합니다.

 

 

- 로그인한 후 "프로젝트 만들기"를 선택합니다.

 

 

- 원하는 프로젝트 이름을 입력하고 만들기.

 

 

- API 및 서비스 사용 설정 클릭.

 

 

- 안드로이드에 적용하니까 Maps SDK for Android 선택.

 

 

- 사용설정 클릭.

 

 

- 사용자 인증 정보 탭 클릭해서 "API 및 서비스의 사용자 인증 정보" 클릭.

 

 

- "사용자 인증 정보 만들기"에서 API 키 클릭.

 

 

- 키가 생성됩니다. 이 API 키를 사용하면 되는데 아직 API 설정이 끝난건 아닙니다. "키 제한"을 클릭.

 

 

- 애플리케이션 제한사항에서 Android를 선택하고, Android 앱의 사용량 제한에 "항목 추가" 클릭.

 

 

- 첫번째 패키지 이름은 Android Studio에서 프로젝트를 생성할 때 만든 패키지를 입력

  두번째 SHA-1 인증서는 CMD창을 열어

 

 

"D:Android\jre\bin\keytool" -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

 

입력해줍니다. "D:Android\jre\bin\keytool"는 keytool파일이 위치한 경로라서 해당파일 경로를 찾아서 입력해줍니다.

 

 

SHA1이라고 적힌부분을 복사해서 입력한 후 완료 클릭.

 

 

이제 좀 전에 발급 받았던 API 키를 가져가서 사용하시면 됩니다!



자바코드에서 색상코드 사용하기


배경색 사용을 예로

 

 

xml에서는 background에 색상코드를 넣어서 사용할 수 있고,

android:background="#bbceff"

 

java에서는 setBackgroundColor에 Color.parseColor("색상코드")를 넣어서 사용하면 됩니다.

textView.setBackgroundColor(Color.parseColor("#bbceff"));

[Android] Chip 사용하기

2020. 6. 7. 14:34

Chip 사용하기

 


build.gradle - dependencies 추가

implementation 'com.android.support:design:28.0.0'

 

xml에 chip 추가

<com.google.android.material.chip.Chip
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="Banana"/>

 

 

이렇게만 해서 실행하면 앱이 정상적으로 실행이 안될 수 있습니다.

values - style.xml에서 style태그 내에 parent를 Theme.MaterialComponents로 시작하는거로 변경해줘야 합니다.

<style name="AppTheme" parent="Theme.MaterialComponents.Light.Bridge">

여기까지는 기초!

 

 

Chipgroup

Chip만 사용할 경우 줄이 가득차면 다음 줄로 넘어가지 않고 계속해서 옆으로 생성된다.

Chipgroup 안에 Chip을 생성하면 알아서 다음 줄에 Chip을 생성한다.

<com.google.android.material.chip.ChipGroup
	android:id="@+id/chipgroup"
	android:layout_width="match_parent"
	android:layout_height="match_parent">
    
    <!-- 코드 작성 -->
    
</com.google.android.material.chip.ChipGroup>

 

 

Chip 테마

Chip에는 4가지 테마가 있습니다.

왼쪽부터 차례로 Action, Entry, Filter, Choice 입니다.

아래와 같이 style을 추가시켜주시면 됩니다.

<com.google.android.material.chip.Chip
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	style="@style/Widget.MaterialComponents.Chip.Action"
	android:text="Banana"/>
<com.google.android.material.chip.Chip
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	style="@style/Widget.MaterialComponents.Chip.Entry"
	android:text="Banana"/>
<com.google.android.material.chip.Chip
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	style="@style/Widget.MaterialComponents.Chip.Filter"
	android:text="Banana"/>
<com.google.android.material.chip.Chip
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	style="@style/Widget.MaterialComponents.Chip.Choice"
	android:text="Banana"/>

 

기타 추가 속성들은 링크를 통해서 확인하실 수 있습니다.

https://material.io/develop/android/components/chip/

 

Chips - Material Components for Android

Chips A Chip represents a complex entity in a small block, such as a contact. It is a rounded button that consists of a label, an optional chip icon, and an optional close icon. A chip can either be clicked or toggled if it is checkable. Chips may be place

material.io

 


+ Recent posts