MainActivity

...더보기
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.example.boostcoursepractice;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
 
import com.google.android.material.snackbar.Snackbar;
 
import org.w3c.dom.Text;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    SingerAdapter adapter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        GridView gridView = (GridView) findViewById(R.id.grid_view);
 
        adapter = new SingerAdapter();
 
        adapter.addItem(new SingerItem("장주느""010-5212-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느1""010-52024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느2""010-51-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느3""0-5-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주4""010-59-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주5""-52 -7024", R.drawable.ic_launcher_background));
 
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SingerItem item = (SingerItem) adapter.getItem(i);
                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();
            }
        });
 
 
 
    }
 
    class SingerAdapter extends BaseAdapter
    {
        ArrayList<SingerItem> items = new ArrayList<SingerItem>() ;
 
        public void addItem(SingerItem item)
        {
            items.add(item);
        }
 
        @Override
        public int getCount() {
            return items.size();
        }
 
        @Override
        public Object getItem(int i) {
            return items.get(i);
        }
 
        @Override
        public long getItemId(int i) {
            return i;
        }
 
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            SingerItemView singerItemView = null ;
 
            if(view == null)
            {
                singerItemView = new SingerItemView(getApplicationContext());
            }
            else
            {
                singerItemView = (SingerItemView) view;
            }
 
            SingerItem item = items.get(i) ;
            singerItemView.setName(item.getName());
            singerItemView.setMobile(item.getMobile());
            singerItemView.setImg(item.getResID());
 
            return singerItemView;
        }
    }
}
 
cs

 

 

.

.

리스트뷰랑 나머지는 다 같아서 생략

.

.

 

 

 

그리드 뷰와 리스트뷰는 아예 사용법이 같다. 다만 그리드뷰의 속성 numColumns를 이용하면 원하는 열의 개수를 지정할 수 있다는 것만 차이가 있다.

 

 

결과화면

MainActivity

...더보기
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
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.boostcoursepractice;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;
 
import com.google.android.material.snackbar.Snackbar;
 
import org.w3c.dom.Text;
 
public class MainActivity extends AppCompatActivity {
 
    String[] items = {"소녀시대""걸스데이""티아라""여자친구"};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        final TextView textView = (TextView) findViewById(R.id.textView);
 
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
 
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        spinner.setAdapter(adapter);
 
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                textView.setText(items[i]);
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                textView.setText("선택안됨");
            }
        });
 
    }
 
}
 
cs

 

activity_main.xml

...더보기
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
<?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"
    >
 
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="395dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.499" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="선택 :"
        android:textSize="40dp"
        app:layout_constraintBottom_toTopOf="@+id/spinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

스피너도 기본적으로 어댑터를 이용하는데 아래와 같이

 

 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);

 

ArrayAdapter가 따로 있어 바로 사용할 수 있다. 

 

 

스피너의 아이템 선택 이벤트처리는 다음과 같이

 

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override

            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                textView.setText(items[i]);

            }

 

            @Override

            public void onNothingSelected(AdapterView<?> adapterView) {

                textView.setText("선택안됨");

            }

        });

 

AdapterView.OnItemSelectedListener를 리스너로 등록해주고 그 안의 onItemSelected, onNothingSelected를 오버라이드 해주면 된다.

 

 

결과화면

MainActivity

...더보기
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
package com.example.boostcoursepractice;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
 
import com.google.android.material.snackbar.Snackbar;
 
import org.w3c.dom.Text;
 
public class MainActivity extends AppCompatActivity {
 
    FrameLayout container ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        container = (FrameLayout) findViewById(R.id.container);
 
        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
                layoutInflater.inflate(R.layout.sum1, container, true);
 
            }
        });
    }
 
}
 
cs

 

activity_main.xml

...더보기
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
<?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"
    >
 
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.151"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />
 
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button">
 
    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

 

sum1.xml           (sub1.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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="부분화면"
        android:textSize="40dp" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>
cs

 

 

 

 

일단 기본적인 객체화 Inflation하는 방법은 다음과 같다

 

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 

                layoutInflater.inflate(R.layout.sum1, container, true);

 

inflate의 첫번째 인자는 어떤 것을 객체화 할 것인지 두번째인자는 어디에 객체화할 것인지 세번째 인자는 바로 붙일 것인지를 나타낸다.

 

 

 

결과 화면

 

 

 

 

BitmapButton(자바 파일)

...더보기
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
45
46
47
48
49
50
51
52
package com.example.boostcoursepractice;
 
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
 
import androidx.appcompat.widget.AppCompatButton;
 
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.ic_kakao);
 
        float textSize = getResources().getDimension(R.dimen.text_size);
        setTextSize(textSize);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
 
        int action = event.getAction() ;
 
        switch (action){
            case MotionEvent.ACTION_DOWN:
                setBackgroundResource(R.drawable.ic_facebook);
                break ;
 
            case MotionEvent.ACTION_UP:
                setBackgroundResource(R.drawable.ic_kakao);
                break;
 
        }
 
        invalidate();
 
        return true ;
    }
}
 
cs

 

 

비트맵 버튼은 AppCompatButton을 상속받아 만들 수 있다. 

 

setTextSize(textSize) 할 때 매개변수는 픽셀단위로 입력 된다. 따라서 dp 단위로 입력하려면 아래와 같이

 

 

values에 dimens.xml을 만들어 주고 <dimen>을 만들어 지정해 주면 된다. 그리고

 

float textSize = getResources().getDimension(R.dimen.text_size);

        setTextSize(textSize);

 

위와 같이 해주면 원하는 dp단위로 지정할 수 있다.

 

 

 

결과화면

 

 

ic_review_selected2.9.png

 

나인패치는

파일명.9.png

이런식으로 확장자앞에 .9.을 가진다.

 

하지만 실제 등록할 때는

android:background="@drawable/ic_review_selected2"

와 같이 .9.을 무시하고 사용된다.

MainActivity

...더보기
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.boostcoursepractice;
 
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import com.google.android.material.snackbar.Snackbar;
 
import org.w3c.dom.Text;
 
public class MainActivity extends AppCompatActivity {
 
    Button btn;
    TextView text;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn = (Button)findViewById(R.id.button);
        text = (TextView)findViewById(R.id.textView);
 
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMessage();
            }
        });
    }
 
    public void showMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("안내");
        builder.setMessage("종료하시겠습니까?");
        builder.setIcon(android.R.drawable.ic_dialog_alert);
 
        builder.setPositiveButton("예"new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Snackbar.make(text, "예 버튼이 눌렸습니다.", Snackbar.LENGTH_LONG).show();
            }
        });
 
        builder.setNegativeButton("아니오"new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Snackbar.make(text, "아니오 버튼이 눌렸습니다.", Snackbar.LENGTH_LONG).show();
            }
        });
 
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }
}
 
cs

 

activity_main.xml

...더보기
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
<?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">
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="알림 대화상자 띄우기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="88dp"
        android:text="대화상자 뷰"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

 

알림 대화 상자는 다음과 같이 builder를 이용하여 설정해주고

 

  AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("안내");

        builder.setMessage("종료하시겠습니까?");

        builder.setIcon(android.R.drawable.ic_dialog_alert);

 

        builder.setPositiveButton("예"new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialogInterface, int i) {

                Snackbar.make(text, "예 버튼이 눌렸습니다.", Snackbar.LENGTH_LONG).show();

            }

        });

 

        builder.setNegativeButton("아니오"new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialogInterface, int i) {

                Snackbar.make(text, "아니오 버튼이 눌렸습니다.", Snackbar.LENGTH_LONG).show();

            }

        });

 

마지막에 

 

AlertDialog alertDialog = builder.create();

        alertDialog.show();

 

create하여 show해주면 된다.

 

 

결과화면

MainActivity

...더보기
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.example.boostcoursepractice;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
import com.google.android.material.snackbar.Snackbar;
 
public class MainActivity extends AppCompatActivity {
 
    Button btn ;
    Button btn2 ;
    Button btn3 ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btn = (Button) findViewById(R.id.button);
 
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast toast = Toast.makeText(getApplicationContext(), "위치가 바뀐 토스트 메세지", Toast.LENGTH_LONG) ;
                toast.setGravity(Gravity.TOP | Gravity.LEFT, 200200);
                toast.show();
            }
        });
 
        btn2 = (Button) findViewById(R.id.button2);
 
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LayoutInflater layoutInflater = getLayoutInflater();
                View layout = layoutInflater.inflate(R.layout.toastborder, (ViewGroup)findViewById(R.id.toast_layout_root));
 
                TextView text = (TextView) layout.findViewById(R.id.tv);
                text.setText("모양을 바꾼 토스트입니다.");
 
                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER, 0-100);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
 
                toast.show();
            }
        });
 
        btn3 = (Button) findViewById(R.id.button3);
 
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "스낵바 입니다.", Snackbar.LENGTH_LONG).show();
            }
        });
    }
}
 
cs

 

drawble/toast.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"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
 
    <stroke
        android:width="4dp"
        android:color="#ffffff00"/>
 
    <solid
        android:color="#ff883300" />
 
    <padding
        android:left="20dp"
        android:bottom="20dp"
        android:right="20dp"
        android:top="20dp"/>
 
    <corners
        android:radius="15dp"/>
</shape>
cs

 

layout/activity_main.xml

...더보기
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
<?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">
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="토스트 띄우기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="56dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:text="토스트 모양 바꾸기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />
 
    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="스낵바 띄우기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

 

layout/toastborder.xml

...더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
 
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/toast"
        android:padding="20dp"
        android:textSize="40dp" />
</LinearLayout>
cs

 

build.gradle(Moudule:app)

...더보기

apply plugin: 'com.android.application'

android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.example.boostcoursepractice"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
compile 'com.android.support:design:29.+'
}

 

기본적으로 Toast 메세지를 띄우는 방법

 

Toast toast = Toast.makeText(getApplicationContext(), "위치가 바뀐 토스트 메세지", Toast.LENGTH_LONG) ;

 

여기서 토스트의 위치를 바꾸려면 

 

toast.setGravity(Gravity.TOP | Gravity.LEFT, 200200);

 

이렇게 하면 된다. 마지막에 toast.show() 하면 토스트 출력

 

 

 

 

토스트의 모양을 바꿔주려면 일단 layout폴더에 xml파일을 만들어주자 여기서는 layout/toastborder.xml을 만들어 주었다. 후에 최상의 뷰그룹인 LinearLayout에 id를 부여한다. 여기서는 android:id="@+id/toast_layout_root 부여 이후에 다시 mainactiviy의 소스코드로 돌아와서 

 

 LayoutInflater layoutInflater = getLayoutInflater();

                View layout = layoutInflater.inflate(R.layout.toastborder, (ViewGroup)findViewById(R.id.toast_layout_root));

 

                TextView text = (TextView) layout.findViewById(R.id.tv);

                text.setText("모양을 바꾼 토스트입니다.");

 

                Toast toast = new Toast(getApplicationContext());

                toast.setGravity(Gravity.CENTER, 0-100);

                toast.setDuration(Toast.LENGTH_LONG);

                toast.setView(layout);

 

                toast.show();

 

이처럼 해주면 된다. 

 

 

추가적으로 

drawble/toast라는 xml을 파일을 만든후 배경을 만들어주고 

layout/toastborder.xml의 TextView에 android:background="@drawable/toast" 이렇게 백그라운드 속성을 지정해주어 모양을 바꾼 토스트 메세지의 배경을 바꾸어 주었다.

 

스낵바의 사용은 아래와 같이 하면 된다.

Snackbar.make(view, "스낵바 입니다.", Snackbar.LENGTH_LONG).show();

단 gradle의 dependencies에 

compile 'com.android.support:design:29.+' 

를 추가해줘야만 사용할 수 있다.

 

버튼1

 

버튼2

 

버튼3

 

MainActivity

...더보기
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package com.example.test;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
 
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    SingerAdapter adapter;
    EditText nameEdit;
    EditText mobileEdit;
    Button button ;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        ListView listView = (ListView) findViewById(R.id.lv);
        nameEdit = (EditText) findViewById(R.id.name_edit);
        mobileEdit = (EditText) findViewById(R.id.mobile_edit);
        button = (Button) findViewById(R.id.button);
 
        adapter = new SingerAdapter();
 
        adapter.addItem(new SingerItem("장주느""010-5212-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느1""010-52024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느2""010-51-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주느3""0-5-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주4""010-59-7024", R.drawable.ic_launcher_background));
        adapter.addItem(new SingerItem("장주5""-52 -7024", R.drawable.ic_launcher_background));
 
 
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SingerItem item = (SingerItem) adapter.getItem(i);
                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();
            }
        });
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = nameEdit.getText().toString();
                String mobile = mobileEdit.getText().toString();
 
                SingerItem item = new SingerItem(name, mobile, R.drawable.ic_launcher_foreground);
 
                adapter.addItem(item);
                adapter.notifyDataSetChanged();
            }
        });
    }
 
    class SingerAdapter extends BaseAdapter
    {
        ArrayList<SingerItem> items = new ArrayList<SingerItem>() ;
 
        public void addItem(SingerItem item)
        {
            items.add(item);
        }
 
        @Override
        public int getCount() {
            return items.size();
        }
 
        @Override
        public Object getItem(int i) {
            return items.get(i);
        }
 
        @Override
        public long getItemId(int i) {
            return i;
        }
 
        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            SingerItemView singerItemView = null ;
 
            if(view == null)
            {
                 singerItemView = new SingerItemView(getApplicationContext());
            }
            else
            {
                singerItemView = (SingerItemView) view;
            }
 
            SingerItem item = items.get(i) ;
            singerItemView.setName(item.getName());
            singerItemView.setMobile(item.getMobile());
            singerItemView.setImg(item.getResID());
 
            return singerItemView;
        }
    }
 
}
cs

 

SingerItem

...더보기
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
package com.example.test;
 
public class SingerItem {
    private String name ;
    private String mobile ;
    private int resID ;
 
    public SingerItem(String name, String mobile, int resID) {
        this.name = name;
        this.mobile = mobile;
        this.resID = resID ;
    }
 
    public String getName() {
        return name;
    }
 
    public String getMobile() {
        return mobile;
    }
 
    public int getResID()
    {
        return resID ;
    }
 
    @Override
    public String toString() {
        return "SingerItem{" +
                "name='" + name + '\'' +
                ", mobile='" + mobile + '\'' +
                ", resID=" + resID +
                '}';
    }
}
 
cs
 

 

SingerItemView

...더보기
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
45
46
47
48
49
50
51
52
53
package com.example.test;
 
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
 
public class SingerItemView extends LinearLayout {
 
    TextView textView;
    TextView textView2;
    ImageView img;
 
    public SingerItemView(Context context) {
        super(context);
 
        init(context);
    }
 
    public SingerItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
 
        init(context);
    }
 
    private void init(Context context)
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.singer_item_view, thistrue);
 
///아래의 방식으로도 인플레이트 할 수 있다.
//View.inflate(getContext() ,R.layout.singer_item_view, this);
 
        textView = findViewById(R.id.tv);
        textView2 = findViewById(R.id.tv2) ;
        img = findViewById(R.id.img) ;
    }
 
    public void setName(String name)
    {
        textView.setText(name);
    }
 
    public void setMobile(String mobile)
    {
        textView2.setText(mobile);
    }
 
    public void setImg(int resID)
    {
        img.setImageResource(resID);
    }
}
 
cs

 

activity_main.xml

...더보기
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
<?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" >
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="false"
        android:orientation="vertical">
 
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="추가" />
 
        <EditText
            android:id="@+id/name_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="이름"
            android:inputType="textPersonName" />
 
        <EditText
            android:id="@+id/mobile_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="전화번호"
            android:inputType="textPersonName" />
 
        <ListView
            android:id="@+id/lv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    </LinearLayout>
</RelativeLayout>
cs

 

singer_item_view.xml

...더보기
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
 
    <ImageView
        android:id="@+id/img"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@mipmap/ic_launcher" />
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="6dp"
        android:orientation="vertical">
 
        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="이름"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30dp" />
 
        <TextView
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="6dp"
            android:text="전화번호"
            android:textColor="@android:color/holo_orange_dark"
            android:textSize="24dp" />
 
    </LinearLayout>
 
</LinearLayout>
cs
 

 

기본 원리는 리스트뷰에 어댑터를 등록하고 어댑터의 안의

ArrayList<SingerItem> items = new ArrayList<SingerItem>() 로 배열을 선언하고

public View getView(int i, View view, ViewGroup viewGroup)을 등록하여 내가 만든 return singerItemView; 을 리턴하여 아이템 항목을 보여주는 식이다. 

 

singerItemView는 singer_item_view.xml과 연결되어 있다. 

 

아래와 같이 클릭리스너를 등록해 리스트의 몇번째 아이템 항목이 선택되었는지를 알수 있다. 

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                SingerItem item = (SingerItem) adapter.getItem(i);

                Toast.makeText(getApplicationContext(), item.toString(), Toast.LENGTH_LONG).show();

            }

        });

 

다음은 버튼을 클릭하여 리스트의 아이템 항목을 추가하는 것인데

  button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                String name = nameEdit.getText().toString();

                String mobile = mobileEdit.getText().toString();

 

                SingerItem item = new SingerItem(name, mobile, R.drawable.ic_launcher_foreground);

 

                adapter.addItem(item);

                adapter.notifyDataSetChanged();

            }

        });

위처럼  adapter.notifyDataSetChanged(); 를 호출하여 어댑터에 변화가 있다고 알려줘야 한다.

 

마지막으로

 public View getView(int i, View view, ViewGroup viewGroup) {

            SingerItemView singerItemView = null ;

 

            if(view == null)

            {

                 singerItemView = new SingerItemView(getApplicationContext());

            }

            else

            {

                singerItemView = (SingerItemView) view;

            }

getView에서 view가 null이 아닐 때 즉 이전에 썼던 객체가 남아있을 때 객체를 더이상 생성하지 않고 재활용하여 객체가 생성되는 수를 줄여 빠르게 만들어 줄 수 있다.

 

결과 화면

+ Recent posts