1. Inflation


XML 레이아웃에서 정의된 내용이 메모리에 객체화되는 것을 말한다.


MainActivity.java 파일에서 activity_main.xml 파일을 이해하려면 

setContentView 메소드의 파라미터로 해당 XML 레이아웃 파일을 지정해주면 내부적으로 인플레이션 과정이 진행된다.


1
2
3
4
5
6
7
8
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
cs


- setContentView() 메소드


화면에 나타낼 뷰를 지정하고, XML 레이아웃의 내용을 메모리 상에 객체화한다.

1
2
public void setContentView (int layoutResID)
public void setContentView (View view [, ViewGroup.LayoutParams params])
cs


XML 레이아웃 파일의 내용이 메모리에 객체로 만들어지면 소스 코드에서는 그 객체들을 찾아 사용할 수 있다.

객체를 찾을 때는 findViewById 메소드를 이용할 수 있으며 

XML 레이아웃에 뷰를 추가할 때 넣어둔 id 속성의 값을 파라미터로 사용한다.


1
Button button = (Button) findViewById(R.id.button1);
cs



2. Layout Inflater

 

- LayoutInflater() 클래스

: 시스템 서비스로 제공되는 클래스로서, 

 전체 화면 중에서 일부분만을 차지하는 화면 구성 요소들을 XML 레이아웃에서 로딩하여 보여준다.


화면 전체를 나타내는 액티비티의 경우에는 setContentView 메소드를 이용해 XML 레이아웃을 인플레이션할 수 있지만, 

XML 레이아웃 파일 안에 포함되지 않는 뷰의 경우에는 setContentView 메소드를 통해 인플레이션되지 않는다.

setContentView 메소드는 액티비티를 위해 만들어 놓은 것이기 때문에 뷰를 위한 인플레이션에는 사용할 수 없다.

실제로 액티비티와 뷰가 내부적으로 관리되는 방식이 달라서 그런 것인데, 이 때문에 뷰의 경우에는 직접 인플레이션을 해야 한다.


레이아웃 인플레이터 객체는 시스템 서비스 객체로 제공되기 때문에 getSystemService 메소드를 이용해 참조할 수 있다.

1
getSystemService(Context.LAYOUT_INFLATER_SERVICE)
cs


뷰 객체가 있으면 그 뷰 객체에 인플레이션한 결과물을 설정하게 된다.

1
2
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.activity_sub, frame_layout, true);
cs


- Layout Inflater Example


XML 레이아웃의 이름은  activity_sub.xml로 만들어져 있고 이 XML 레이아웃에 들어가 있는 뷰들은 메모리에 객체로 만들어진 후에 frame_layout 뷰 객체에 설정된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MainActivity extends AppCompatActivity {
    
    Button button;
    FrameLayout frame_layout;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = (Button)findViewById(R.id.button);
        frame_layout = (FrameLayout)findViewById (R.id.frame_layout);
        
        button.setOnClickListener(new View.onClickListener(){
            @Override
            public void onClick(View v){
                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                inflater.inflate(R.layout.activity_sub, frame_layout, true);
            }
        });
    }
}
cs


이런 방식은 새로운 뷰를 정의할 때 자주 볼 수 있는데, 동적으로 레이아웃이 변경, 추가되는 경우에도 사용된다.





출처: https://www.edwith.org/boostcourse-android/lecture/17056/

'Android' 카테고리의 다른 글

ListView (리스트뷰) - 예제  (0) 2018.05.06
ListView (리스트뷰)  (0) 2018.05.06
Bitmap Button 만들기  (0) 2018.05.01
Nine Patch (나인패치)  (0) 2018.05.01
AlertDialog (알림 대화상자)  (0) 2018.04.28

ButtonImg.zip


1. Bitmap button을 사용하는 이유


나인패치(9-patch) 이미지를 적용하는 대표적인 경우가 버튼인데, 

배경 부분을 이미지로 지정하여 만든 버튼은 눌러도 이미지의 변화가 없어 

사용자가 버튼을 눌렀는지 안 눌렀는지 알 수 없다는 단점이 있다.

비트맵 이미지를 이용하여 버튼의 상태를 이벤트로 구분해 표시할 수 있다.



2. 실행 결과 화면


기본 화면과 터치 시 화면


   



3. BitmapButton.java


버튼을 상속해서 새로운 버튼을 생성한다.

터치된 상태에 따라 배경 이미지를 바꾸어주기 위해 터치 이벤트를 이용해 처리한다.

invalidate 메소드를 사용하여 바뀐 이미지를 화면을 갱신한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.tistory.qlyh8.pracitice;
 
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;
import android.view.MotionEvent;
 
public class BitmapButton extends AppCompatButton {
    public BitmapButton(Context context) {
        super(context);
        init(context);
    }
 
    public BitmapButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
 
    private void init(Context context){
        setBackgroundResource(R.drawable.btn1);
        setTextSize(context.getResources().getDimension(R.dimen.text_size));
        setTextColor(Color.RED);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        int action = event.getAction();
 
        switch (action){
            case MotionEvent.ACTION_DOWN:
                setBackgroundResource(R.drawable.btn2);
                break;
            case MotionEvent.ACTION_UP:
                setBackgroundResource(R.drawable.btn1);
                break;
        }
        invalidate();
 
        return true;
    }
}
 
cs



4. values/dimens.xml


1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="text_size">25dp</dimen>
</resources>
cs



5. activity_main.xml


뷰를 상속해서 새로운 뷰를 만든 경우에는 XML 레이아웃에 추가할 때 패키지 명까지 같이 넣어준다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.tistory.qlyh8.pracitice.MainActivity">
   
   <qlyh8.tistory.com.pracitice.BitmapButton
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Hello World!"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent" />
 
</android.support.constraint.ConstraintLayout>
 
cs





출처: https://www.edwith.org/boostcourse-android/lecture/17055/

'Android' 카테고리의 다른 글

ListView (리스트뷰)  (0) 2018.05.06
Inflation (인플레이션)  (0) 2018.05.01
Nine Patch (나인패치)  (0) 2018.05.01
AlertDialog (알림 대화상자)  (0) 2018.04.28
Snackbar (스낵바)  (0) 2018.04.28

1. 9 Patch


이미지가 늘어나거나 줄어들 때 생기는 이미지 왜곡을 해결하는 방법이다.

원래 이미지보다 한 픽셀씩 크게 만들고 가장자리 픽셀에는 늘어날 수 있는지, 늘어나면 안 되는지를 색상으로 구분하여 넣어준다.


이미지 파일 이름에 .9 라는 글자를 붙여준다.

예를 들어, person.png 라는 이미지 파일을 나인패치 방식으로 만들었다면 person.9.png 라는 이름으로 바꿔야 한다.

이렇게 바꾼 이름은 안드로이드에서 동일하게 R.drawable.person으로 인식한다.


나인패치 이미지라고 인식하기 때문에 이미지를 늘릴 때 특정 부분만 늘려주게 된다.

깨질 가능성이 있는 부분은 늘리지 않아서 이미지의 크기가 늘어나더라도 덜 왜곡된 이미지를 보여줄 수 있다.



2. Reference link


- 크기 조정 가능한 비트맵 생성 (9-패치 파일 만들기)

  https://developer.android.com/studio/write/draw9patch.html?hl=ko


- 안드로이드 나인 패치(9-Patch) 이미지 버튼 만들기

  http://recipes4dev.tistory.com/132


- Simple nine-patch generator (일반 이미지를 나인패치 이미지로 변환)

  http://romannurik.github.io/AndroidAssetStudio/nine-patches.html#&sourceDensity=320&name=example





출처: https://www.edwith.org/boostcourse-android/lecture/17054/

'Android' 카테고리의 다른 글

Inflation (인플레이션)  (0) 2018.05.01
Bitmap Button 만들기  (0) 2018.05.01
AlertDialog (알림 대화상자)  (0) 2018.04.28
Snackbar (스낵바)  (0) 2018.04.28
Toast (토스트)  (0) 2018.04.28

+ Recent posts