728x90

https://material.io/resources/color/ 사이트에 접속한다.

 

 

위와 같은 기본 UI 구성을 할 수 있도록 구성되어 있다.

먼저 Primary 를 선택하고 색상표에서 원하는 색상을 선택한다.

그 다음에 Secondary를 선택하고 원하는 색상을 선택한다.

Text on P 도 마찬가지로 색상을 선택하거나 Custom에서 선택한다.

 

 

내가 예시로 선택한 화면이다.

 

이제 Export를 눌러서 Android를 선택하여 저장하면 color.xml 파일로 저장된다.

 

<!--?xml version="1.0" encoding="UTF-8"?-->
<resources>
  <color name="primaryColor">#2196f3</color>
  <color name="primaryLightColor">#6ec6ff</color>
  <color name="primaryDarkColor">#0069c0</color>
  <color name="secondaryColor">#ededed</color>
  <color name="secondaryLightColor">#ffffff</color>
  <color name="secondaryDarkColor">#bbbbbb</color>
  <color name="primaryTextColor">#ffffff</color>
  <color name="secondaryTextColor">#000000</color>
</resources>

 

Material Design color palettes

https://material.io/design/color/the-color-system.html#tools-for-picking-colors 사이트에 색상표가 잘 표현되어 있다.

 

스타일 및 테마

https://developer.android.com/guide/topics/ui/look-and-feel/themes?hl=ko 

 

스타일 및 테마  |  Android 개발자  |  Android Developers

스타일 및 테마 Android에서 스타일 및 테마를 사용하면 웹 디자인의 스타일시트와 유사하게 앱 디자인의 세부사항을 UI 구조 및 동작과 분리할 수 있습니다. 스타일은 단일 View의 모양을 지정하는

developer.android.com

 

Theme 와 Dark Theme 를 고려하여 List Item 의 구분선을 표시하고자 할 때

<solid android:color="?attr/backgroundColor"/> 와 같이 배경색 지정을 Theme 와 Dark Theme 각각 다르게 인식할 수 있도록 ?attr/backgroundColor 로 처리하면 된다.

 

res/drawable/bg_border.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:aapt="http://schemas.android.com/aapt">
    <item>
        <shape android:shape="rectangle">
            <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="1dp"/>
            <stroke android:width="1dp" android:color="#ebebeb"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="?attr/backgroundColor"/>
        </shape>
    </item>
</layer-list>
 

 

디자인 감각 부족으로 테마 색상 표현력이 부족 하지만, backgroundColor 는 흰색과 검은색으로 테마에 따라 구분되어지는 걸 확인할 수 있다.

어두운 테마(Dark Theme)는 Android 10 (API 레벨 29) 이상에서 제공된다.

MaterialComponents의 어두운 테마 설정을 사용할 수도 있다.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/blue_700</item>
        <item name="colorPrimaryVariant">@color/blue_200</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">#ff625b71</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="backgroundColor">@color/white</item>
    </style>
</resources>
 
<!-- Dark Theme -->
<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/blue_500</item>
        <item name="colorPrimaryVariant">@color/blue_200</item>
        <item name="colorOnPrimary">@color/black</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">#ffccc2dc</item>
        <item name="colorSecondaryVariant">@color/teal_200</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
        <item name="backgroundColor">@color/black</item>
    </style>
</resources>

 

http://android-doc.github.io/training/material/theme.html 에 각 영역의 색상 폰 이미지를 참조하면 된다.

'안드로이드 > Layout' 카테고리의 다른 글

CoordinatorLayout custom toolbar  (0) 2021.08.29
Material Components color  (0) 2021.08.19
Shape Drawable로 간단한 배경 이미지 활용  (0) 2021.08.12
CardView tools:visibility  (0) 2021.08.12
android 검색 + 버튼 배치  (0) 2021.03.14
블로그 이미지

Link2Me

,
728x90

CoordinatorLayout 은 기본 API가 아닌 Support Design Widget 이다.

 

앱 build.gradle 추가

dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    implementation 'com.google.android.material:material:1.1.0'
}

 

Layout 구성 형태

 

AppBarLayout
안드로이드에는 원래 ActionBar가 기본적으로 제공되고 있었지만, 액션바는 안드로이드 API 버전마다 다른 기능과 다른 동작을 제공해 개발자가 사용자에게 일관된 UX를 제공하는 데 불편함이 있었다.
이에 대한 해결책으로 google은 material design 패키지에 있는 AppBarLayout과 ToolBar를 제시하고 있다.

 

activity_customer.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    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=".ui.CustomerActivity">
 
    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.Base.AppBarOverlay">
 
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.Base.PopupOverlay" />
    </com.google.android.material.appbar.AppBarLayout>
 
    <include layout="@layout/content_customer_detail"/>
 
</androidx.coordinatorlayout.widget.CoordinatorLayout>
 

content_customer_detail.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:padding="@dimen/screen_edge_margin"
    android:background="@color/colorWhite"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".ui.CustomerActivity"
    tools:showIn="@layout/activity_customer" >
 
    <WebView
        android:id="@+id/custHomepageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</LinearLayout>

 

툴바 Home 버튼을 누르면 현재 Activity 를 스택에서 제거하는 코드가 아래 포함되어 있다.

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
 
class CustomerActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_customer)
        context = this@CustomerActivity
 
        setSupportActionBar(toolbar)
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setDisplayShowHomeEnabled(true)
        }
 
    }
 
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.getItemId()) {
            android.R.id.home -> {
                finish() // toolbar HOME 버튼 누르면 현재 Activity 스택에서 제거
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
 
    override fun onBackPressed() {
        finish()
    }
}
 

 

기본 툴바가 아니라 커스텀 툴바로 버튼 아이콘을 추가하고 싶을 때가 있다.

이럴 경우 아래와 같이 수정하면 된다.

 

res/menu/menu_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<menu 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"
    tools:context=".ui.CustomerActivity">
    <item
        android:id="@+id/edit"
        android:icon="@drawable/ic_edit_white_24dp"
        android:title="편집"
        app:showAsAction="always" />
</menu>

 

drawable/ic_edit_white_24dp.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
  <path
      android:pathData="M14.06,9.02l0.92,0.92L5.92,19L5,19v-0.92l9.06,-9.06M17.66,3c-0.25,0 -0.51,0.1 -0.7,0.29l-1.83,1.83 3.75,3.75 1.83,-1.83c0.39,-0.39 0.39,-1.02 0,-1.41l-2.34,-2.34c-0.2,-0.2 -0.45,-0.29 -0.71,-0.29zM14.06,6.19L3,17.25L3,21h3.75L17.81,9.94l-3.75,-3.75z"
      android:fillColor="#ffffff"/>
</vector>

 

 

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
 
class CustomerActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_customer)
        context = this@CustomerActivity
 
        setSupportActionBar(toolbar)
        supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setDisplayShowHomeEnabled(true)
        }
 
    }
 
    // 커스텀 메뉴 추가 목적 (menu 폴더에 있는 xml 파일)
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_edit, menu)
        return true
    }
 
    override fun onOptionsItemSelected(item: MenuItem): Boolean = when(item.itemId) {
        android.R.id.home -> {
            finish() // toolbar HOME 버튼 누르면 현재 Activity 스택에서 제거
            true
        }
        R.id.edit -> {
            finish()
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
 
    override fun onBackPressed() {
        finish()
    }
}
 

 

'안드로이드 > Layout' 카테고리의 다른 글

Material Design Color TOOL 사용법  (0) 2021.09.10
Material Components color  (0) 2021.08.19
Shape Drawable로 간단한 배경 이미지 활용  (0) 2021.08.12
CardView tools:visibility  (0) 2021.08.12
android 검색 + 버튼 배치  (0) 2021.03.14
블로그 이미지

Link2Me

,
728x90

Material Components color 색상 예시

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">@color/green_700</color>
    <color name="colorPrimaryVariant">@color/blue_700</color>
    <color name="colorSecondary">@color/green_200</color>
    <color name="colorSecondaryVariant">@color/green_500</color>
 
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
 
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="deep_purple_200">#B39DDB</color>
    <color name="deep_purple_500">#673AB7</color>
 
    <color name="blue_200">#90CAF9</color>
    <color name="blue_500">#2196f3</color>
    <color name="blue_600">#1e88e5</color>
    <color name="blue_700">#1976d2</color>
    <color name="light_blue_200">#81D4FA</color>
    <color name="light_blue_500">#03A9F4</color>
 
    <color name="green_200">#03dac6</color>
    <color name="green_500">#018786</color>
    <color name="green_700">#00A99D</color>
    <color name="light_green_200">#C5E1A5</color>
    <color name="light_green_500">#8BC34A</color>
 
    <color name="red_200">#cf6679</color> <!--Color error (dark)-->
    <color name="red_500">#f44336</color>
    <color name="red_600">#b00020</color> <!--Color error (light)-->
 
    <color name="pink_200">#F48FB1</color>
    <color name="pink_500">#E91E63</color>
 
    <color name="indigo_200">#9FA8DA</color>
    <color name="indigo_500">#3F51B5</color>
 
    <color name="cyan_200">#80DEEA</color>
    <color name="cyan_500">#00BCD4</color>
 
    <color name="lime_200">#E6EE9C</color>
    <color name="lime_500">#CDDC39</color>
 
    <color name="yellow_200">#FFF59D</color>
    <color name="yellow_500">#FFEB3B</color>
 
    <color name="amber_200">#FFE082</color>
    <color name="amber_500">#FFC107</color>
 
    <color name="orange_200">#FFCC80</color>
    <color name="orange_500">#FF9800</color>
    <color name="deep_orange_50">#fbe9e7</color>
    <color name="deep_orange_200">#FFAB91</color>
    <color name="deep_orange_300">#ff8a65</color>
    <color name="deep_orange_500">#FF5722</color>
    <color name="deep_orange_700">#e64a19</color>
 
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_500">#009688</color>
    <color name="teal_700">#FF018786</color>
 
    <color name="black">#FF000000</color>
    <color name="black_800">#121212</color> 
 
    <color name="white">#FFFFFFFF</color>
    <color name="background">#eee</color>
 
    <color name="transparent">#00000000</color><!-- 투명 -->
    <color name="transparentBlack">#96000000</color>
 
    <color name="colorBlack">#ff000000</color>
    <color name="colorIvory">#fffff0</color>
    <color name="colorWhite">#ffffffff</color>
    <color name="colorWhiteGray">#f0f0f0</color>
    <color name="colorGray">#ff8a8a8a</color>
    <color name="colorDarkGray">#4c4c4e</color>
    <color name="colorLightGray">#ffeaeaea</color>
    <color name="colorMint">#ff00c0aa</color>
    <color name="colorLightMint">#1000c0aa</color>
    <color name="colorRed">#ffD81B60</color>
    <color name="colorLightRed">#ffff4444</color>
    <color name="colorOrangeDark">#ffff8800</color>
    <color name="colorYellow">#ffFFEC19</color>
    <color name="colorBlue">#0385ff</color>
    <color name="colorSkyBlue">#87ceeb</color>
    <color name="colorYellowGreen">#9acd32</color>
    <color name="colorGreenYellow">#adff2f</color>
    <color name="colorGreen">#00ff00</color>
 
    <color name="colorTitle">#de000000</color>
    <color name="colorDetail">#8a000000</color>
 
    <color name="colorDivider">#1f000000</color>
 
</resources>

 

블로그 이미지

Link2Me

,
728x90

https://developer.android.com/guide/topics/resources/drawable-resource?hl=ko#Shape 

 

드로어블 리소스  |  Android 개발자  |  Android Developers

드로어블 리소스는 화면에 그릴 수 있으며 getDrawable(int)와 같은 API를 사용하여 가져오거나 android:drawable 및 android:icon과 같은 특성을 사용하여 다른 XML 리소스에 적용할 수 있는 그래픽에 대한 일

developer.android.com

를 참고하면 된다.

 

실제로 비트맵을 사용하지  않아도 되므로 APK 파일 용량도 줄어들고 색상 변경이 편리하다.

 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#FF7272" />
    <size
        android:width="44dp"
        android:height="44dp" />
</shape>

oval : 타원형

rectangle : 사각형(default)

 

Layout 파일에서 사용법

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:gravity="center"
    app:layout_constraintTop_toBottomOf="@id/addButton"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent">
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/circle_red"
        android:gravity="center"
        android:textColor="@color/white"
        android:textSize="18sp"
        android:textStyle="bold"
        android:visibility="gone"
        tools:visibility="visible"
        tools:text="1" />
 
</LinearLayout>

shape_drawable.zip
0.00MB

 

kotlin 코드

private fun setNumberBackground(number:Int, textView: TextView) {
    when(number) {
        in 1..10 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_yello)
        in 11..20 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_blue)
        in 21..30 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_red)
        in 31..40 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_gray)
        else -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_green)
 
    }
}

'안드로이드 > Layout' 카테고리의 다른 글

CoordinatorLayout custom toolbar  (0) 2021.08.29
Material Components color  (0) 2021.08.19
CardView tools:visibility  (0) 2021.08.12
android 검색 + 버튼 배치  (0) 2021.03.14
하단 TabLayout + ViewPager2 Layout 예제  (0) 2020.12.30
블로그 이미지

Link2Me

,
728x90

CardView를 쓰면 입체감을 줄 수 있는데, 단 하나의 레이아웃만을 가질 수 있다.
아이템 전체를 CardView 로 만들려면 <LinearLayout>...</LinearLayout> 으로 모든 내용을 감싸야 한다.

 

Android Studio 에서 Layout 의 default 는 gone 으로 처리하고, 디자인하는 화면에서는 보이게 하고 싶을 때가 있다.

android:visibility="gone"

tools:visibility="visible"

<?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:id="@+id/view_business_card"
    android:layout_width="match_parent"
    android:visibility="gone"
    tools:visibility="visible"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:clickable="true"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
 
    </LinearLayout>
 
</androidx.cardview.widget.CardView>
 

 

블로그 이미지

Link2Me

,
728x90

LinearLayout 에서 horizontal 로 검색어를 배치하는 방법이다.

<LinearLayout 
     android:layout_height="wrap_content" 
     android:layout_width="match_parent"
     android:orientation="horizontal" >
<EditText
     android:layout_height="wrap_content" 
     android:layout_weight="1"
     android:layout_width="0dp"/>
 <Button
    android:text="Button"
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"/>
 </LinearLayout>

별로 깔끔한 디자인이 아니라서 Material Design 을 적용해서 테스트해 봤다.

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

    <com.google.android.material.textfield.TextInputLayout
	style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
	android:layout_width="0dp"
	android:layout_height="wrap_content"
	android:layout_weight="1"
	app:shapeAppearance="@style/ShapeAppearance.MaterialComponents.MediumComponent"
	app:boxStrokeColor="@color/blue_500"
	app:endIconMode="clear_text"
	android:hint="검색어"
	android:layout_marginLeft="5dp"
	android:layout_marginRight="5dp">

	<com.google.android.material.textfield.TextInputEditText
	    android:id="@+id/list_search_edit"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.button.MaterialButton
	android:id="@+id/list_search_btn"
	style="@style/Widget.MaterialComponents.Button.OutlinedButton"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_gravity="center_vertical"
	android:layout_marginRight="5dp"
	app:strokeColor="@color/blue_700"
	app:strokeWidth="1dp"
	android:text="검색"
	android:textSize="18sp" />

</LinearLayout>

그러나 원하는 결과가 나오지 않았다.

 

android SearchView 기능을 이용하여 원하는 결과를 얻을 수 있다.

<androidx.appcompat.widget.SearchView
    android:id="@+id/list_search_edit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    app:iconifiedByDefault="false"
    app:queryHint="검색어를 입력하세요"/>

Java 소스코드 처리

import androidx.appcompat.widget.SearchView;

SearchView search_view;
private ArrayList<Group_Item> groupItemList = new ArrayList<>(); // 서버에서 가져온 원본 데이터 리스트

search_view = findViewById(R.id.list_search_edit);
search_view.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
	// do something on text submit
	searchData(query);
	return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
	if(newText.length() == 0){
	    groupItemList.clear();
	}
	return false;
    }
});

검색어를 입력할 때마다 데이터를 서버에서 가져오는 것은 원하는 결과가 아닌 거 같아서

검색어를 입력하고 나서 검색 아이콘을 눌렀을 때 서버로부터 결과를 가져오고,

검색어를 삭제하면 ArrayList 데이터를 초기화하는 로직을 사용했다.

블로그 이미지

Link2Me

,
728x90

https://link2me.tistory.com/1898 게시글은 ViewPager와 Fragment 함께쓰기 예제에 대한 사항이다.

동일 코드 중심으로 ViewPager2 와 Fragment 함께쓰기로 변경했을 경우에 대한 사항을 적어둔다.


https://developer.android.com/training/animation/vp2-migration?hl=ko 게시글을 먼저 읽어보면 도움된다.


기존의 ViewPager 와 변경된 점은 RTL 슬라이딩(좌에서 우로) 지원, 수직방향 슬라이드 지원, 기존 ViewPager의 notifyDataSetChanged 버그 문제해결, offscreenPageLimit를 통한 뷰 계층에 저장된 뷰나 프레그먼트를 제어할 수 있다.


Fragment를 사용하기 위해 FragmentPagerAdapter나 FragmentStatePagerAdapter대신 FragmentStateAdapter를 사용해야 한다.



Layout 에서의 변경사항


앱 build.gradle 추가사항

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.2.1'
    // ViewPager2
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
    implementation 'gun0912.ted:tedpermission:2.0.0'
}
 


ViewPagerActivity.java 변경사항

기존 ViewPager 코드

    private ViewPager mViewPager;
    private MyViewPagerAdapter myPagerAdapter;
    private TabLayout tabLayout;
 

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Fragment frag1 = new HomeFragment().newInstance(code,"");
        Fragment frag2 = new WebviewFragment().newInstance(code,"https://m.naver.com");
        Fragment frag3 = new AddressFragment().newInstance(code);


        mViewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tab_layout);
        mViewPager.setOffscreenPageLimit(5);

        myPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        myPagerAdapter.addFrag(frag1,"Home");
        myPagerAdapter.addFrag(frag2,"공지");
        myPagerAdapter.addFrag(frag3,"지도");

        mViewPager.setAdapter(myPagerAdapter);
        tabLayout.setupWithViewPager(mViewPager);

   }

ViewPager2 코드

    private ViewPager2 mViewPager;
    private MyViewPagerAdapter myPagerAdapter;
    private TabLayout tabLayout;

    private String[] titles = new String[]{"리스트", "웹뷰", "연락처"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Fragment frag1 = new HomeFragment().newInstance(code,"");
        Fragment frag2 = new WebviewFragment().newInstance(code,"https://m.naver.com");
        Fragment frag3 = new AddressFragment().newInstance(code);

        mViewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tab_layout);

        myPagerAdapter = new MyViewPagerAdapter(this);
        myPagerAdapter.addFrag(frag1);
        myPagerAdapter.addFrag(frag2);
        myPagerAdapter.addFrag(frag3);

        mViewPager.setAdapter(myPagerAdapter);

        //displaying tabs
        new TabLayoutMediator(tabLayout, mViewPager, (tab, position) -> tab.setText(titles[position])).attach();
    }
 


MyViewPagerAdapter.java

public class MyViewPagerAdapter extends FragmentStateAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();

    public MyViewPagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    public void addFrag(Fragment fragment) {
        mFragmentList.add(fragment);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        // Fragment 교체를 보여주는 처리 구현
        return mFragmentList.get(position);
    }

    @Override
    public int getItemCount() {
        // ViewPager 로 보여줄 View의 전체 개수
        return mFragmentList.size();
    }

}


전체 코드는 https://github.com/jsk005/JavaProjects/tree/master/viewpager2 에 올려 두었다.


참고하면 도움되는 자료

https://www.androidhive.info/2020/01/viewpager2-pager-transformations-intro-slider-pager-animations-pager-transformations/



'안드로이드 > Layout' 카테고리의 다른 글

CardView tools:visibility  (0) 2021.08.12
android 검색 + 버튼 배치  (0) 2021.03.14
하단 TabLayout + ViewPager Layout 예제  (0) 2020.11.01
LinearLayout 예제  (0) 2020.10.13
LinearLayout 동적 생성  (0) 2020.10.01
블로그 이미지

Link2Me

,
728x90

Android Material Design 기반 TabLayout 을 하단에 두고, ViewPager 를 상단에 두는 Layout 예제이다.




ViewPager : 좌우로 스와프하며 View를 전환하는 AdapterView


<?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=".ViewPagerActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/vp_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/tab_layout">

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        app:tabTextColor="@color/colorDarkGray"
        app:tabSelectedTextColor="@color/colorWhite"
        app:layout_collapseMode="pin"
        app:tabGravity="fill"
        app:tabBackground="@drawable/tab_color_selector"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/vp_layout">

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

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

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

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

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

    </com.google.android.material.tabs.TabLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
 


전체 코드는 https://github.com/jsk005/JavaProjects/tree/master/viewpager 에 올려두었다.

Fragment 기반 WebView 코드를 포함했고, 뒤로 가기 버튼 동작하도록 하는 걸 구글링해서 추가했다.

'안드로이드 > Layout' 카테고리의 다른 글

android 검색 + 버튼 배치  (0) 2021.03.14
하단 TabLayout + ViewPager2 Layout 예제  (0) 2020.12.30
LinearLayout 예제  (0) 2020.10.13
LinearLayout 동적 생성  (0) 2020.10.01
SMS authentication with OTP Layout Example  (0) 2020.09.14
블로그 이미지

Link2Me

,
728x90

LineaLayout 지식인 질의 예제


<?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:padding="24dp"
    android:weightSum="6.5">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="horizontal"
        android:layout_weight="2">

        <View
            android:id="@+id/view1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FF0000"
            android:layout_weight="1" />

        <View
            android:id="@+id/view2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#0000FF"
            android:layout_weight="1" />

        <View
            android:id="@+id/view3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00FF00"
            android:layout_weight="1" />
    </LinearLayout>

    <View
        android:id="@+id/view4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#FFFF00"
        android:layout_weight="1"/>

    <View
        android:id="@+id/view5"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#0000FF"
        android:layout_weight="1"/>

    <View
        android:id="@+id/view6"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="#00FF00"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_marginTop="20dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Button"
                android:textAllCaps="false"/>

            <ImageButton
                android:id="@+id/imageButton"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_gravity="center"
                android:src="@drawable/ic_baseline_videocam_24" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="20192019"
                android:textSize="32sp"
                android:textColor="#FF0000"/>

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="24dp"
                android:text="홍길동"
                android:textSize="32sp"
                android:textColor="#0000FF"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
 



Vector Asset 추가하는 방법으로 이미지를 추가하면 된다.

'안드로이드 > Layout' 카테고리의 다른 글

하단 TabLayout + ViewPager2 Layout 예제  (0) 2020.12.30
하단 TabLayout + ViewPager Layout 예제  (0) 2020.11.01
LinearLayout 동적 생성  (0) 2020.10.01
SMS authentication with OTP Layout Example  (0) 2020.09.14
EditText DatePicker  (0) 2020.08.18
블로그 이미지

Link2Me

,
728x90

LinearLayout 동적 생성 코드이다.


import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout myLinearLayout = new LinearLayout(this);
        myLinearLayout.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        final EditText editText = new EditText(this);
        editText.setHint("여기에 입력하세요");
        mParams.setMargins(0,50,0,10);
        editText.setLayoutParams(mParams);
        myLinearLayout.addView(editText);

        DisplayMetrics dm = getResources().getDisplayMetrics();
        int size = Math.round(20 * dm.density);

        Button btn = new Button(this);
        btn.setText("버튼");
        btn.setBackgroundColor(Color.YELLOW);
        mParams.topMargin = size;
        btn.setLayoutParams(mParams);
        myLinearLayout.addView(btn);

        LinearLayout.LayoutParams tv_params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        final TextView textView = new TextView(this);
        textView.setText("텍스트뷰입니다.");
        textView.setTextColor(Color.MAGENTA);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
        tv_params.gravity = Gravity.CENTER;
        tv_params.setMargins(0,50,0,0);
        textView.setLayoutParams(tv_params);
        myLinearLayout.addView(textView);

        setContentView(myLinearLayout);

        btn.setOnClickListener(view -> textView.setText(editText.getText().toString()));
    }

}


결과 화면


 


코드파일 및 결과 이미지

dynamicLayout.zip


'안드로이드 > Layout' 카테고리의 다른 글

하단 TabLayout + ViewPager Layout 예제  (0) 2020.11.01
LinearLayout 예제  (0) 2020.10.13
SMS authentication with OTP Layout Example  (0) 2020.09.14
EditText DatePicker  (0) 2020.08.18
Floating Action Button  (0) 2020.07.11
블로그 이미지

Link2Me

,
728x90

Cutstom Dialog 기능을 이용하여 SMS authentication with One Time Password 처리를 위한 Layout 구성 예제이다.


custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/parent_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/parent_card_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <RelativeLayout
            android:id="@+id/inner_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparent">

            <com.google.android.material.textview.MaterialTextView
                android:id="@+id/dialog_title_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/default_title_text"
                android:textSize="20sp"
                android:textStyle="bold"
                android:textColor="@android:color/black"
                android:textAlignment="center"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:paddingTop="5dp"
                android:paddingBottom="2dp"/>

            <com.google.android.material.textview.MaterialTextView
                android:id="@+id/dialog_explain_text"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/dialog_title_text"
                android:text="@string/default_explain_text"
                android:textSize="14sp"
                android:textColor="@android:color/black"
                android:textAlignment="center"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:paddingTop="2dp"
                android:paddingBottom="5dp"/>

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/et_auth_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/dialog_explain_text"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp" >

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/et_auth_text"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorWhite"
                    android:textSize="16sp"
                    android:hint="@string/prompt_auto"
                    android:inputType="numberDecimal"
                    android:imeOptions="actionDone"
                    android:selectAllOnFocus="true">

                </com.google.android.material.textfield.TextInputEditText>

            </com.google.android.material.textfield.TextInputLayout>

            <LinearLayout
                android:id="@+id/btn_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:layout_below="@id/et_auth_layout"
                android:gravity="top"
                android:orientation="horizontal">

                <com.google.android.material.button.MaterialButton
                    android:id="@+id/btn_disagree"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorOrangeDark"
                    app:cornerRadius="10dp"
                    android:text="취소" />

                <com.google.android.material.button.MaterialButton
                    android:id="@+id/btn_agree"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_weight="1"
                    android:backgroundTint="@color/colorBlue"
                    app:cornerRadius="10dp"
                    android:text="전송" />

            </LinearLayout>
        </RelativeLayout>
    </androidx.cardview.widget.CardView>
</RelativeLayout>
 


예제의 코드는 https://github.com/jsk005/JavaProjects/tree/master/Interfaces/src/main/java/com/link2me/android/interfaces 에 올려져 있다.

Custom Dialog 를 Interface로 처리하는 코드 예제일 뿐이지 SMS OTP 인증 전체 코드는 아니다.


'안드로이드 > Layout' 카테고리의 다른 글

LinearLayout 예제  (0) 2020.10.13
LinearLayout 동적 생성  (0) 2020.10.01
EditText DatePicker  (0) 2020.08.18
Floating Action Button  (0) 2020.07.11
CardView Layout 예제  (0) 2020.04.12
블로그 이미지

Link2Me

,
728x90

날짜를 선택하여 입력하는 EditText 예제이다.


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="5dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="70dp"
        android:layout_height="30dp"
        android:layout_marginTop="5dp"
        android:text="운행일자"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="@color/colorBlack"/>

    <EditText
        android:id="@+id/et_drivingDate"
        android:layout_width="120dp"
        android:layout_height="30dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="20dp"
        android:background="#E3E8EA"
        android:gravity="center"
        android:focusable="false"
        android:inputType="date"/>

</LinearLayout> 


public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    Context mContext;

    //Declaring EditText
    private EditText et_drivingDate;
    String drivingDate; // 운행일자
    final Calendar myCalendar = Calendar.getInstance();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        initView();
    }

    private void updateLabel() {
        String myFormat = "yyyy-MM-dd"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

        et_drivingDate.setText(sdf.format(myCalendar.getTime()));
    }

    private void initView() {
        //Initializing the views
        et_drivingDate = findViewById(R.id.et_drivingDate);
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateLabel();
            }

        };
        et_drivingDate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new DatePickerDialog(MainActivity.this, date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });

    }
}


'안드로이드 > Layout' 카테고리의 다른 글

LinearLayout 동적 생성  (0) 2020.10.01
SMS authentication with OTP Layout Example  (0) 2020.09.14
Floating Action Button  (0) 2020.07.11
CardView Layout 예제  (0) 2020.04.12
Meterial Design 로그인 Layout 예제  (0) 2020.03.21
블로그 이미지

Link2Me

,
728x90

Floating Action Button 은 화면에 떠있는 버튼으로 머터리얼 디자인에서 자주 사용하는 기본 위젯이다.

 

https://www.youtube.com/watch?v=cASXtRa6yDc 동영상을 보면 이해될 것이다.

 

 

앱 build.gradle 추가사항

dependencies {
    implementation 'com.google.android.material:material:1.1.0'
}

 

 

ConstraintLayout 의 모든 보기에는 가로 및 세로 제약조건을 각각 하나 이상 추가해야 한다.

 

 

아래 그림에서 ConstraintLayout 에서 버튼의 위치를 결정하는 것은 1번과 2번이다.

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"

 

 

 

5번을 누르면 floating 버튼의 색상을 쉽게 변경할 수 있다.

6번은 floating 버튼 안의 이미지를 작성하는 것이다.

Vector Drawable을 사용하고 롤리팝 미만의 기기를 지원해야 할 때는 src 대신에 srcCompat 속성을 사용해야 한다.

 

 

 

 

검색으로 원하는 이미지를 찾아도 된다.

 

이름이 자동으로 추가된 것을 확인할 수 있다.

 

 

 

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fabMain"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:backgroundTint="#00BCD4"
        android:tooltipText="메시지 전송"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:srcCompat="@drawable/ic_baseline_menu_24"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

public class MainActivity extends AppCompatActivity {

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

        FloatingActionButton fab = findViewById(R.id.fabMain);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view,"실제 클릭 이벤트를 대신 보여준다.",Snackbar.LENGTH_LONG)
                        .setAction("Action",null)
                        .show();
            }
        });
    }
}
 

 

테스트 파일 첨부 (Java 기반 코드인데 코틀린으로 변환 목적으로 앱 build.gradle이 코틀린 관련 추가되어 있음)

floatingbutton.zip
다운로드

 

코틀린으로 코드를 변환해보자.

 

자동변환 전후 Java코드와 kotlin 코드를 보자.

FloatingActionButton fab = findViewById(R.id.fabMain);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Snackbar.make(view,"실제 클릭 이벤트를 대신 보여준다.",Snackbar.LENGTH_LONG)
                .setAction("Action",null)
                .show();
    }
});

val fab = findViewById<FloatingActionButton>(R.id.fabMain)
fab.setOnClickListener { view ->
    Snackbar.make(view, "실제 클릭 이벤트를 대신 보여준다.", Snackbar.LENGTH_LONG)
        .setAction("Action", null)
        .show()
}

 

코틀린 코드를 좀 더 정리하면....

fabMain.setOnClickListener { view ->
    Snackbar.make(view, "실제 클릭 이벤트를 대신 보여준다.", Snackbar.LENGTH_LONG)
        .setAction("Action", null)
        .show()
}

 

'안드로이드 > Layout' 카테고리의 다른 글

SMS authentication with OTP Layout Example  (0) 2020.09.14
EditText DatePicker  (0) 2020.08.18
CardView Layout 예제  (0) 2020.04.12
Meterial Design 로그인 Layout 예제  (0) 2020.03.21
ScrollView  (0) 2019.12.20
블로그 이미지

Link2Me

,
728x90

앱 build.gradle 추가사항

implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.1.0'


ConstraintLayout 을 이용하여 Layout 구성





<?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"
    android:id="@+id/cardview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    app:cardCornerRadius="1dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/listitem_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/listitem_title"
            app:srcCompat="@drawable/photo_base" />

        <TextView
            android:id="@+id/listitem_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="성명"
            android:textSize="20dp"
            android:layout_marginLeft="10dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/listitem_subtitles"
            app:layout_constraintStart_toEndOf="@+id/listitem_image"
            app:layout_constraintTop_toTopOf="parent" />

        <LinearLayout
            android:id="@+id/listitem_subtitles"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:orientation="vertical"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/listitem_checkbox"
            app:layout_constraintStart_toEndOf="@+id/listitem_title"
            app:layout_constraintTop_toTopOf="parent">

            <TextView
                android:id="@+id/listcell_subtext1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="서브타이틀1"
                android:textColor="@color/colorBlack"
                android:textSize="14dp"
                android:textStyle="normal" />

            <TextView
                android:id="@+id/listcell_subtext2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="서브타이틀2"
                android:textColor="@color/colorBlack"
                android:textSize="14dp"
                android:textStyle="normal" />

        </LinearLayout>

        <CheckBox
            android:id="@+id/listitem_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:visibility="gone"
            android:layout_marginLeft="20dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/listitem_subtitles" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>


<?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"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/item_listview" />

</androidx.constraintlayout.widget.ConstraintLayout>
 


'안드로이드 > Layout' 카테고리의 다른 글

EditText DatePicker  (0) 2020.08.18
Floating Action Button  (0) 2020.07.11
Meterial Design 로그인 Layout 예제  (0) 2020.03.21
ScrollView  (0) 2019.12.20
Dynamic Layouts  (0) 2019.01.06
블로그 이미지

Link2Me

,
728x90

Meterial Design 로그인 예제 Layout 을 적어둔다.


<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingBottom="@dimen/activity_vertical_margin">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="300dp"
                android:gravity="center"
                android:text="Login"
                android:textStyle="bold"
                android:textSize="45dp"
                android:fontFamily="cursive"
                android:textColor="@color/colorWhite"
                android:layout_marginTop="0dp"
                android:background="@drawable/logo"/>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:layout_marginRight="20dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/et_id"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorWhite"
                    android:autofillHints="@string/prompt_id"
                    android:hint="아이디"
                    android:selectAllOnFocus="true" />

            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.textfield.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:layout_marginRight="20dp">

                <com.google.android.material.textfield.TextInputEditText
                    android:id="@+id/et_pw"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:autofillHints="@string/prompt_pw"
                    android:hint="비밀번호"
                    android:background="@color/colorWhite"
                    android:imeOptions="actionDone"
                    android:inputType="textPassword"
                    android:selectAllOnFocus="true" />

            </com.google.android.material.textfield.TextInputLayout>

            <com.google.android.material.button.MaterialButton
                android:id="@+id/btn_login"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="50dp"
                android:layout_marginRight="20dp"
                android:padding="10dp"
                android:text="로그인"
                android:textColor="@color/colorWhite"
                android:textSize="16sp"
                android:textStyle="bold"
                app:backgroundTint="@color/colorMint"
                app:cornerRadius="20dp" />

        </LinearLayout>
    </FrameLayout>

</ScrollView>


이미지 파일

logo.zip



'안드로이드 > Layout' 카테고리의 다른 글

Floating Action Button  (0) 2020.07.11
CardView Layout 예제  (0) 2020.04.12
ScrollView  (0) 2019.12.20
Dynamic Layouts  (0) 2019.01.06
Android Fragment 기본 예제  (0) 2018.09.11
블로그 이미지

Link2Me

,

ScrollView

안드로이드/Layout 2019. 12. 20. 21:57
728x90

Android Layout 을 작성하다보면 종종 ScrollView를 사용하는 경우가 있다. ScrollView는 길어지는 높이로 인해 화면에서 일부 View가 잘리는 현상을 상하 스크롤을 통해 해소할 수 있는 View이다.

 

주의할점: 스크롤뷰에는 단 하나의 자식 View만 포함되어야 한다!!
그래서, 여러개의 View를 넣으려면 스크롤뷰 안에 LinearLayout(
리니어레이아웃) 또는 RelativeLayout 등의 ViewGroup을 자식 View로 지정하고 그 안에 다양한 View를 넣는 구조를 택하여 해결할 수 있다.

 

<ScrollView
    android:id="@+id/scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity ="center"
    android:fillViewport="true"
    android:layout_marginTop="0dp"
    android:background="#000000">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
 
        <TextView
            android:id="@+id/info"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:gravity="left"
            android:textColor="#FFFFFF"/>
 
        <TextView
            android:id="@+id/consoleText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:ellipsize="start"
            android:gravity="left"
            android:textColor="#FFFFFF"
            android:textStyle="bold" />
    </LinearLayout>
</ScrollView> 

 

아래 코드는 콘솔 앱에 사용된 코드 일부이다.

 

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Context mContext;
    TextView mTitleTextView;
    TextView mDumpTextView;
    ScrollView mScrollView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        initView();
    }
    private void initView() {
        mTitleTextView = (TextView) findViewById(R.id.info);
        mDumpTextView = (TextView) findViewById(R.id.consoleText);
        mScrollView = findViewById(R.id.scrollview);
        mScrollView.setVerticalScrollBarEnabled(true); // 수직방향 스크롤바 사용 가능하도록 설정
        mDumpTextView.setMovementMethod(new ScrollingMovementMethod());
        mDumpTextView.setTextSize(Constants.mTextFontSize);
        mDumpTextView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mDumpTextView.setTextIsSelectable(true); // 복사 가능
                mDumpTextView.setCursorVisible(true);
                SpannableString highlightString = new SpannableString(mDumpTextView.getText());
                highlightString.setSpan(new BackgroundColorSpan(ContextCompat.getColor(mContext, R.color.mediumspringgreen))
                        , 0, mDumpTextView.getText().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                return false;
            }
        });
        mDumpTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDumpTextView.setTextIsSelectable(true); // 복사 가능
                mDumpTextView.setCursorVisible(false);
            }
        });
    }
    private void updateReceivedData(String data) {
        final String message = data;
        mDumpTextView.setTextColor(Color.WHITE);
        mDumpTextView.append(message);
        mDumpTextView.setTextIsSelectable(false); // 텍스트 클립보드 복사
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mDumpTextView.setElegantTextHeight(true);
        }
        mDumpTextView.setImeOptions(EditorInfo.IME_FLAG_NO_ENTER_ACTION);
        mDumpTextView.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        mDumpTextView.setSingleLine(false);
        refreshView();
    }
    private void refreshView(){
        mScrollView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        },100);
        mScrollView.smoothScrollTo(0, mDumpTextView.getBottom());
    }

 

'안드로이드 > Layout' 카테고리의 다른 글

CardView Layout 예제  (0) 2020.04.12
Meterial Design 로그인 Layout 예제  (0) 2020.03.21
Dynamic Layouts  (0) 2019.01.06
Android Fragment 기본 예제  (0) 2018.09.11
FloatingActionButton(FAB)  (0) 2018.08.15
블로그 이미지

Link2Me

,
728x90

출처 : https://stackoverflow.com/questions/17070047/how-to-set-layout-dynamically-in-android


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LayoutParams default_layout_params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    View view1 = inflater.inflate(R.layout.layout1, null);
    addContentView(view1, default_layout_params);          
    View view2 = inflater.inflate(R.layout.layout2, null);
    addContentView(view2, default_layout_params);
    view2.setVisibility(View.INVISIBLE);
    view1.setVisibility(View.VISIBLE);
    view1.bringToFront();
} 


private View view1, view2;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view1 = getLayoutInflater().inflate(R.layout.layout1, null);
    view2 = getLayoutInflater().inflate(R.layout.layout2, null);
    setContentView(view1);

    someBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(view2);
        }
    });


    someBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(view1);
        }
    });
}


'안드로이드 > Layout' 카테고리의 다른 글

Meterial Design 로그인 Layout 예제  (0) 2020.03.21
ScrollView  (0) 2019.12.20
Android Fragment 기본 예제  (0) 2018.09.11
FloatingActionButton(FAB)  (0) 2018.08.15
LinearLayout weight  (0) 2018.03.01
블로그 이미지

Link2Me

,
728x90

안드로이드 Fragment 예제를 간략하게 정리했다.

API Level 11(Android 3.0) 이상에서 지원한다. 요즈음에는 최소 4.4 이상으로 컴파일을 하므로 기본적으로 제공된다고 볼 수 있다.


Fragment를 사용하는 가장 큰 목적은 분할된 화면들을 독립적으로 구성하고 그 상태를 관리하는데 있다.

Fragment는 항상 Activity 위에 올라가 있어야 한다.

Activity 로 만들어진 화면을 분할하여 각각의 부분화면을 Fragment로 만들고 그 Fragment를 독립적으로 관리하는 것을 목표로 한다.


Fragment는 항상 Activity 내에 포함되어 있어야 하며 해당 Fragment의 수명 주기는 호스트 Activity의 수명 주기에 직접적으로 영향을 받는다.
예를 들어 Activity가 일시정지되는 경우, 그 안의 모든 Fragment도 일시정지되며 Activity가 소멸되면 모든 Fragment도 마찬가지로 소멸된다. 그러나 Activity가 실행 중인 동안에는 각 Fragment를 추가 또는 제거하는 등 개별적으로 조작할 수 있다.


Activity 의 UI를 보여주기 위해서 onCreate 메소드를 Override 하고 Layout Resource ID인 R.layout.activity_main을 파라미터로 넘기면서 setContentView 메소드를 호출한다.


먼저, MainActivity 에 표시될 Layout XML 구조는 아래에 버튼을 클릭하면 Fragment 화면이 변경되도록 구성했다.


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

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_above="@+id/tabmenuLayout" />

    <LinearLayout
        android:id="@+id/tabmenuLayout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true" >

        <Button
            android:id="@+id/btn_tab1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Tab 1"/>

        <Button
            android:id="@+id/btn_tab2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Tab 2"/>

        <Button
            android:id="@+id/btn_tab3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Tab 3"/>

    </LinearLayout>
</RelativeLayout>


fragment_container 에 표시될 Fragment XML 은 다음과 같다.

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

    <TextView
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="프래그먼트 1" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffe4e1">

    <TextView
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="프래그먼트 2" />

</RelativeLayout>

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

    <TextView
        android:id="@+id/fr_tv03"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:text="프래그먼트 3"
        android:textStyle="bold"/>

</RelativeLayout>


Fragment01.java

Alt + Insert 키를 눌러서 아래 메소드를 추가한 다음에 view를 return해 주도록 코드를 수정한다.

Fragment는 Fragment Class 를 상속하여 만들 수 있다.

 public class Fragment01 extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        // onCreateView() : 프래그먼트와 연관된 뷰 계층을 생성하기 위해 호출됨
        // Inflate the layout for this fragment
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_01, container, false);
        return rootView;
        //return super.onCreateView(inflater, container, savedInstanceState); // Alt + Insert키 누르면 자동 생성되는 return
    }
}


Fragment02.java

- Activity 에서 전달한 데이터를 받아서 화면에 표시하기

- Fragment 로 데이터 전달법은 구글에서 Passing data to activity and fragment in Android 로 검색하면 된다.

- onCreateView 에서 Activity 에서 전달한 데이터를 받아도 된다.

public class Fragment02 extends Fragment {
    TextView textView;
    String strtext;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            strtext = getArguments().getString("edttext"); // Activity 에서 받은 데이터
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_02, container, false);
        textView = (TextView) rootView.findViewById(R.id.fr_tv02);
        textView.setText(strtext);
        return rootView;
        //return super.onCreateView(inflater, container, savedInstanceState);
    }
}


Fragment03.java

 public class Fragment03 extends Fragment {
    TextView textView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        // onCreateView()로 전달된 container 매개변수가 상위 ViewGroup 이며(액티비티의 레이아웃으로부터), 이 안에 프래그먼트 레이아웃이 삽입
        // savedInstanceState 매개변수는 Bundle이며, 프래그먼트가 재개되는 중에 프래그먼트의 이전 인스턴스에 대한 데이터를 제공
        // Inflate the layout for this fragment
        // Inflate 시키고자 하는 Layout 의 Resource ID, Inflated 된 Layout 의 상위가 될 ViewGroup
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_03, container, false);
        textView = (TextView) rootView.findViewById(R.id.fr_tv03);
        textView.setText("Fragment 3을 선택했네요.");
        return rootView;
    }
}


MainActivity.java

Activity에서 Fragment를 불러오는 기능을 수행

 public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Context context;
    private Button tab1, tab2, tab3;
    private Fragment fragment = null;

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

        tab1 = findViewById(R.id.btn_tab1);
        tab2 = findViewById(R.id.btn_tab2);
        tab3 = findViewById(R.id.btn_tab3);

        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);
        tab3.setOnClickListener(this);

        if(findViewById(R.id.fragment_container) != null){
            if(savedInstanceState != null) return;
            Fragment01 fragment01 = new Fragment01();
            fragment01.setArguments(getIntent().getExtras());

            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            // add() 메서드를 사용하여 프래그먼트를 추가하고, 추가할 프래그먼트와 이를 삽입할 뷰를 지정
            fragmentTransaction.add(R.id.fragment_container, fragment01);
            // FragmentTransaction을 변경하고 나면, 반드시 commit()을 호출해야 변경 내용이 적용됨
            fragmentTransaction.commit();
        }
        // 상세 설명은 https://developer.android.com/guide/components/fragments?hl=ko 참조
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_tab1:
                fragment = new Fragment01();
                changeFragment(fragment);
                break;
            case R.id.btn_tab2:
                Bundle bundle = new Bundle();
                bundle.putString("edttext", "From Activity");
                fragment = new Fragment02();
                fragment.setArguments(bundle); // Fragment 로 데이터 전달
                changeFragment(fragment);
                break;
            case R.id.btn_tab3:
                fragment = new Fragment03();
                changeFragment(fragment);
                break;
        }
    }

    private void changeFragment(Fragment fragment) {
        // 프로그래밍 방식으로 프래그먼트를 기존의 ViewGroup에 추가
        // 액티비티가 실행 중인 동안에는 언제든 액티비티 레이아웃에 프래그먼트를 추가 가능
        // 액티비티 내의 프래그먼트를 관리하려면 FragmentManager를 사용해야 함.
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container,fragment);
        //fragmentTransaction.addToBackStack(null); // back 버튼을 눌렀을 때 동작하는 옵션.
        fragmentTransaction.commit(); // 트랜잭션을 액티비티에 적용하려면 반드시 commit()을 호출해야 함.
    }
}


Fragment는 Activity가 아니기 때문에 context를 갖지 않는다.
Fragment 구현시 context를 이용해야 할 경우 getActivity()함수를 이용한다.
getActivity().getApplicationContext();
getActivity().finish();
getActivity().getSharedPreferences("pref", Activity.MODE_PRIVATE);
getActivity().getSystemService(Context.USB_SERVICE);
getActivity().getSystemService(getActivity().CLIPBOARD_SERVICE);


테스트 파일

src.zip


사양이 낮은 폰에서 테스트를 못해봤는데 만약 동작되지 않는다면, import 수정.

http://www.androhub.com/android-pass-data-from-activity-to-fragment/ 에 나오는 import 참조하면 될 듯....


참조하면 도움되는 게시글

http://family-gram.tistory.com/60


'안드로이드 > Layout' 카테고리의 다른 글

ScrollView  (0) 2019.12.20
Dynamic Layouts  (0) 2019.01.06
FloatingActionButton(FAB)  (0) 2018.08.15
LinearLayout weight  (0) 2018.03.01
Android ViewFlipper(뷰플리퍼)  (0) 2017.05.02
블로그 이미지

Link2Me

,
728x90

FloatingActionButton(FAB)
UI 위에 떠 있는 동그라미 모양에 아이콘처럼 되어 사용되는 버튼이다.

build.gradle 추가 사항
dependencies {
    implementation 'com.google.android.material:material:1.1.0'
}

layout 예시
CoordinatorLayout 의 자식 레이아웃에 Floating Action Button 을 추가

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

    <include layout="@layout/view_drawer" />

    <include layout="@layout/content_body" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="#60CEDC"
        app:srcCompat="@android:drawable/ic_menu_camera" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>


activity 코드
// Floating Action Button을 리스트 뷰에 적용
FloatingActionButton fab = findViewById(R.id.fab);
fab.attachToListView(listView);
// 이벤트 적용
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
});

'안드로이드 > Layout' 카테고리의 다른 글

Dynamic Layouts  (0) 2019.01.06
Android Fragment 기본 예제  (0) 2018.09.11
LinearLayout weight  (0) 2018.03.01
Android ViewFlipper(뷰플리퍼)  (0) 2017.05.02
Fragment 화면 이동  (0) 2017.03.26
블로그 이미지

Link2Me

,
728x90

LinearLayout의 자식 View에는 가중치를 부여할 수 있다.

가중치는 layout_weight 로 표현되며 가중치는 정수로 표현되며 자식뷰의 중요도를 나타낸다.

LinearLayout 의 자식 View들의 가중치가 각각 1, 2, 3 이면 남아있는 공간의 1/6, 2/6, 3/6을 각각 할당한다.

자식 View의 가중치를 지정하지 않으면 android:layout_weight="0" 으로 간주하고 확장하지 않는다.

 

layout_gravity : 부모 컨테이너의 여유 공간에 View가 모두 채워지지 않아 여유 공간 안에서 View를 정렬할 때

gravity : View 에서 화면에 표시하는 내용물을 정렬할 때

 

 

weight는 비율을 주는 속성인데 width나 height중 비율을 주고싶은 속성에 0dp를 줘야한다.
여기선 한줄을 똑같이 나눠가지길 원하니까 width의 값에 0dp를 주어야한다.
또 항목들을 감싸고 있는 레이아웃에 weigthSum값을 지정해 주어야 하는데 이것은 선택사항이다.
weight는 비율 값이라 0.00~1.00까지의 값을 가진다.

weighSum은 하위 각각 레이아웃 weight의 값의 합이 되어야 하며 값을 초과하게될 경우 레이아웃이 View에서 벗어나게 된다.

 

<?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"
    android:orientation="horizontal"
    android:weightSum="5">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="3" />

</LinearLayout>

 

 

실전 예제

<?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="wrap_content"
    android:orientation="vertical">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:background="@drawable/bg_border">
 
        <TextView
            android:id="@+id/line_rank"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1.5"
            android:layout_gravity="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textColor="?android:attr/textColorSecondary"
            android:gravity="center"
            android:textStyle="bold"
            tools:text="1" />
 
        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="@color/colorDivider"
            android:layout_gravity="center_vertical"
            android:layout_marginEnd="15dp"
            android:layout_marginStart="10dp"/>
 
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_weight="5"
            android:orientation="vertical">
 
            <TextView
                android:id="@+id/line_name"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:gravity="left|center_vertical"
                android:ellipsize="end"
                android:maxLines="1"
                android:singleLine="true"
                android:text="가든파이브"
                android:textColor="@color/colorDarkGray"
                android:textAppearance="?textAppearanceSubtitle1"
                android:textSize="14dp" />
 
            <TextView
                android:id="@+id/line_address"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:gravity="left|center_vertical"
                android:ellipsize="end"
                android:singleLine="true"
                android:maxLines="1"
                android:textColor="#999"
                android:textSize="11dp"
                android:textAppearance="?textAppearanceSubtitle1"
                tools:text="서울시 송파구 문정동 충민로 66" />
 
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="@android:color/transparent"
            android:layout_gravity="center"
            android:orientation="vertical">
            <TextView
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="부동산"/>
 
            <TextView
                android:id="@+id/estate"
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textColor="@color/blue_700"
                android:maxLines="1"
                android:text="50"/>
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="@android:color/transparent"
            android:layout_gravity="center"
            android:orientation="vertical">
            <TextView
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="계약자"/>
 
            <TextView
                android:id="@+id/contractor"
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textColor="@color/blue_700"
                android:maxLines="1"
                android:text="50"/>
        </LinearLayout>
 
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="@android:color/transparent"
            android:layout_gravity="center"
            android:orientation="vertical">
            <TextView
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="예약자"/>
 
            <TextView
                android:id="@+id/reservation"
                style="?attr/textAppearanceSubtitle2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:textColor="@color/blue_700"
                android:maxLines="1"
                android:text="50"/>
        </LinearLayout>
 
    </LinearLayout>
</LinearLayout>

 

https://link2me.tistory.com/2039 에 Android Material Design 적용한 칼라 색상 정리해 놓은 자료가 있다.

'안드로이드 > Layout' 카테고리의 다른 글

Android Fragment 기본 예제  (0) 2018.09.11
FloatingActionButton(FAB)  (0) 2018.08.15
Android ViewFlipper(뷰플리퍼)  (0) 2017.05.02
Fragment 화면 이동  (0) 2017.03.26
안드로이드 Layout  (0) 2016.07.23
블로그 이미지

Link2Me

,