https://www.youtube.com/watch?v=xgpLYwEmlO0

 

본 내용은 위 강의의 내용을 참조하였습니다.

 

이번에는 리사이클 뷰의 아이템을 클릭 시 

아이템 내용에 대해 구체적인 설명을 하는 액티비티를 생성하는 

기능을 추가해보겠습니다. 

 

 

우선 클릭시 등장하는 액티비티를 만들어 보겠습니다.

 

 

empty 액티비티 하나를 생성합니다. 

 

컴포넌트 트리에 위와 같이 이미지 뷰와 텍스트 뷰 2개를 등록합니다.

ConstraintLayout은 이제 어느 정도 하실 수 있을 겁니다.

혹시 안된다면 위의 동영상을 참조해주세요

 

 

 

이런 느낌으로 만들어 주세요

전 이미지가 커서 이미지 뷰 가로 세로 크기를

100dp로 고정시켰습니다.

다음으로 my_row로 돌아가서 카드뷰가 부모로 하는 ConstraintLayout의 아이디를 만들어주세요

클릭 리스너에 등록을 위해 필요합니다. 

아이디 등록이 끝났다면, 어댑터의 뷰 홀더로 돌아가서 등록합니다.

 

 

아이템이 클릭되면  자세한 설명이 있는 액티비티로 넘기기 위해 아래와 같이

layout에 리스너를 설정합니다.

 

자세한 설명이 있는 액티비티로 누른 아이템의 정보도 같이 putExtra로 담아줍니다.

 

이제 자세한 설명이 있는 액티비티로 넘어옵니다.

코드는 아래와 같이 작성합니다.

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.recyclerview;
 
 
 
public class Main2Activity extends AppCompatActivity {
 
    ImageView mainImageView;
    TextView title, description;
 
    String data1, data2;
    int myImage;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
 
        mainImageView = findViewById(R.id.imageView2);
        title = findViewById(R.id.textView3);
        description = findViewById(R.id.textView4);
 
        getData();
        setData();
    }
 
    private void getData(){
        if(getIntent().hasExtra("images"&&
                getIntent().hasExtra("title"&& getIntent().hasExtra("description"))
        {
            data1 = getIntent().getStringExtra("title");
            data2 = getIntent().getStringExtra("description");
            myImage = getIntent().getIntExtra("images"1);
 
        } else{
            Toast.makeText(this,"No data", Toast.LENGTH_SHORT).show();
        }
 
 
    }
 
    private void setData() {
        title.setText(data1);
        description.setText(data2);
        mainImageView.setImageResource(myImage);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

이 코드의 핵심은 getData함수 소스라 할 수 있습니다.

getIntent.hasExtra()를 통해 인텐트에 담겨온 데이터가 있는지 여부를 판별합니다.

있다면 getStringExtra와 getIntExtra를 통해 데이터를 받아옵니다.

이제 받아온 데이터를 setData()함수를 통해서 값을 넣어줍니다.

 

강아지를 클릭해보겠습니다.

 

소스코드는 깃허브에 있습니다.

https://github.com/3210439/RecyclerView

https://www.youtube.com/watch?v=18VcnYN5_LM

본 내용은 위의 강의를 참조하였습니다.

 

오늘은 위의 이미지와 같은 리사이클 뷰를 만들어 보겠습니다.

 

리사이클 뷰에 대해 소개하겠습니다.

리사이클 뷰는 사용자가 관리하는 수의 데이터 집합을 개별 아이템 단위로 구성하여

화면에 출력하는 뷰 그룹이며, 한 화면에 표시되기 힘든 많은 수의 데이터를 스크롤 가능한 리스트로

표시해주는 위젯 이라고 합니다.

 

또한, 리사이클 뷰는 기존에 사용되던 listView에 유연함과 성능을 더한 것으로

구글에서도 이제 listView보다는 리사이클 뷰를 사용할 것을 권고한다고 하네요

 

코딩으로 넘어가겠습니다.

프로젝트를 생성 하였다면 

리사이클 뷰를 레이아웃 디자인에서 RecyclerView 검색을 통해

레이아웃 안에 넣어줍니다.

 

위 화면에서 OK를 누르게 되면 자동적으로, RecylerView에 필요한 라이브러리를 

추가해줍니다. 

 

 

그래들 앱 수준에서 보면

recylerview:1.1.0이 추가된 것을 확인할 수 있습니다.

 

다음으로, string 배열을 생성 합니다.

strings.xml로 이동합니다.

 

 

위와 같이 리사이클 뷰의 아이템 이름과, 설명의 배열을

생성하였습니다.

 

다음으로는 이미지를 준비합시다. 

저 같은 경우는 동물 이미지가 있기 때문에 

활용하도록 하겠습니다. 

 

 

이미지들을 Ctrl+c, Ctrl+v를 통해 drawable 폴더에 넣어줍니다.

 

 

이제, 메인 액티비티에서 배열들을 생성해줍니다.

참고로 이미지 배열에 들어가는 R 주소들은

string-array에 생성했던 동물들 순서로 해주시기 바랍니다.

일치하지 않을 경우 이미지는 고양이인데 이름은 고양이가 아닐 수 도 있습니다.

 

 

다음으로 리사이클 뷰를 위한 어뎁터 클래스를 생성합니다.

 

위와 같이 MyAdapter라는 자바 파일을 생성하고

RecyclerView.Adapter를 부모로 합니다.

빨간 부분은 alt+enter를 눌러서

Create class 'MyViewHolder'를 선택하면 됩니다.

 

 

계속해서 위와 같이 작성합니다.

 

빨간 줄은 빨간줄 선택 후 alt+enter에서

Implement methods를 선택하여 해결합니다.

다음으로 어댑터에 데이터를 전달하기 위해서

생성자를 생성하고

매개변수는 아까 만들어두었던 배열들을 전달하기 위한

형태로 만듭니다.

 

메인 액티비티로 돌아가서 어댑터를 생성합니다.

 

 

이제

리사이클 뷰의 아이템의 형태를 만들어야 합니다.

layout폴더에 xml 파일을 생성합니다.

 

LinearLayout을 ConstraintLayout으로 변경합니다.

그리고 CardView를 넣어줍니다.

 

자동으로 라이브러리를 임포트

 

카드뷰에 레이아웃을 넣어주고

레이아웃 안에 이미지 뷰, 텍스트뷰1, 텍스트뷰2를 넣어줍니다.

 

다음으로 레이아웃을

이렇게 배치하겠습니다.

우선 이미지를 클릭합니다

그러면 우측에

 

화면이 뜹니다.

파란색 원안에 +표시가 돼있는 4개의 원을

모두 클릭합니다.

동쪽 방향 원은 다시 풀고 클릭 후 누른 상태를 유지한 상태에서

오른쪽 끝에다 가져다 둡니다.

 

 

이 상태에서

아래의 값이 50이 되어있을 것인데 그것을 0으로 바꿔주면

 

위와 같이 이미지가 왼쪽에 붙게 됩니다.

 

이번엔 텍스트 뷰를 조정합니다.

위 이미지처럼 만들기 위해

우선 위쪽 텍스트를 클릭해 +표시 파랑원을 모두 클릭하고

다음 밑에 텍스트도 같은 작업을 반복합니다.

그리고 2개의 수치를

이렇게 맞춰주세요

근대 텍스트 간 간격이 8+8이되

너무 큽니다.

아래 텍스트의 북쪽 margin 값을 0으로 줍니다.

 

이제 제목은 굵은 글씨로 만들고 크게 만듭시다.

 

위 텍스트뷰 속성에

위 이미지 설정을 추가해주세요

 

그러면

 

아래와 같이 됩니다. 텍스트 값으로 Title과 description을 각각 텍스트뷰에 넣어주세요 

 

이제 거의 다 됐습니다.

카드뷰가 부모로 하는

Contraintlayout의 height를 wrap_parent로 바꿔주세요

안 그러면 화면에 한 개의 행 밖에 안 보여 준다네요 

그리고, height 아래 android:layout_margin="10dp"

을 추가해주세요

 

다음으로 위의 카드뷰 +원을 모두 클릭하여 주세요 그러면 빨간 줄이 사라집니다.

 

이제 다시 어댑터로 돌아옵니다.

이제 현재 만들어준 아이템을 휴대폰에 띄우기 위해서 사용대는 메서드

onCreateViewHolder를 아래와 같이 작성합니다.

인플레이터는 부풀리는 것이라는 뜻으로 해석해 볼 수 있는데

이 친구가 리사이클 뷰에 속해있는 아이템을 휴대폰에 그리는 역할을 합니다.

이제 이미지가 생성되었으니 

이미지에 값을 넣기 위해서 아이디 변수를 생성 후 아이디를 각각 넣어줍시다.

이 작업은 ViewHolder에서 진행됩니다.

이제 값을 전달할 수 있게 되었습니다.

값 전달은 onBindViewHolder에서 진행합니다.

bind란 묶다란 뜻으로 텍스트에 값을 넣겠다란 뜻으로 해석할 수 있을 거 같습니다.

 

마지막으로, getItemCount 아이템의 개수를 알려주는 메서드를 설정합시다.

어댑터 설정이 끝났으니 리사이클 뷰에 어댑터를 연결합시다.

 

 

이런 뭔가가 잘못됐군요 이미지 크기가 매우 크게 나온 것으로 보아

my_row로 돌아가서 이미지 뷰 크기를 wrap_content에서 60dp로 

수정하겠습니다.

 

 

이제 잘되는군요

 

소스코드는 깃허브에 올려 두었습니다.

https://github.com/3210439/RecyclerView

 

3210439/RecyclerView

Contribute to 3210439/RecyclerView development by creating an account on GitHub.

github.com

 

안녕하세요! 여러분들 오늘은 SharedPreference에 대해 알아보아요

간단한 로그인 기능을 구현해볼 것입니다.

 

1) 프로젝트를 생성합니다.

empty 설정 해주세요

 

2) xml 코드를 작성합니다.

코드를 작성하다가 android:onClick="erase" 에서는 붉은 줄이 생길 텐데요,

그러면 alt + enter 키로 자바 폴더에 생성하기 를 하시면 간단하게 

터치 기능을 사용할 수 있습니다.

 

 

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
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
 
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="60dp"
        android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginBottom="32dp"
        android:orientation="vertical"
        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="match_parent"
            android:layout_height="wrap_content"
            android:text="로그인"
            android:textStyle="bold"
            android:gravity="center"
            android:textSize="25sp"/>
 
        <EditText
            android:layout_marginTop="30dp"
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="ID 입력"
            android:inputType="textPersonName" />
 
        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="비밀번호 입력"
            android:inputType="textPersonName" />
 
        <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_weight="1"
                android:onClick="erase"
                android:text="지우기" />
 
            <Button
                android:id="@+id/button2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="confirm"
                android:text="로그인" />
 
        </LinearLayout>
 
        <CheckBox
            android:layout_marginTop="10dp"
            android:id="@+id/checkBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="아이디 저장하기"
            />
 
    </LinearLayout>
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

 

따라 해 보시면 위의 이미지와 같이 됩니다. 

위의 이미지를 보면 아이디 저장하기라는 체크 박스가 있습니다.

체크가 된 상태인지 onStop메서드가 호출될 때 확인할 것이며

체크가 되었다면 sharedPreference를 사용하여 File이라는

파일에 아이디를 저장해 둘 것입니다. 

 

3) Java파일 코드를 작성합니다.

이번엔 기능을 넣기 위해 자바 파일을 설정합니다.

 

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
package com.example.test_sharedpreference;
 
import android.content.SharedPreferences;
 
 
public class MainActivity extends AppCompatActivity {
 
    private EditText editText1;
    private EditText editText2;
    private CheckBox checkBox;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText1 = findViewById(R.id.editText);
        editText2 = findViewById(R.id.editText2);
        checkBox = findViewById(R.id.checkBox);
 
        //File이란 파일로 저장해둔 값을 가져오기위한 설정
        SharedPreferences sf = getSharedPreferences("File",MODE_PRIVATE);
        //text1에 값이 있으면 가져오고 두번째 인자는 없을경우 가져오는 값이다.
        String text1 = sf.getString("text1","");
 
        // text!가 그냥 공백이 아니라면 아이디 저장이된 상태이기 때문에 체크박스를
        // 체크 상태로 변환한다.
        if(!(text1.equals("")))
            checkBox.setChecked(true);
 
        editText1.setText(text1);
 
 
    }
 
    public void erase(View view) {
        editText1.setText("");
        editText2.setText("");
    }
 
    public void confirm(View view) {
 
    }
 
    @Override
    protected void onStop() {
        super.onStop();
 
        SharedPreferences sharedPreferences = getSharedPreferences("File",MODE_PRIVATE);
        //저장을 하기위해 editor를 이용하여 값을 저장시켜준다.
 
        //체크 박스에 체크가 됬다면 아이디를 저장한다.
        if(checkBox.isChecked()) {
            String text1 = editText1.getText().toString();
            editor.putString("text1", text1);
        }
        else
        {
            editor.putString("text1""");
        }
 
        // 값을 다 넣었으면 commit으로 완료한다.
        editor.commit();
    }
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

이상으로 sharedPreference를 사용해 보았습니다. 

혹시 궁금한 것이 있다면 댓글로 남겨주세요 

 

소스코드는 깃허브에 있습니다.

https://github.com/3210439/test_sharedPreference

 

3210439/test_sharedPreference

Contribute to 3210439/test_sharedPreference development by creating an account on GitHub.

github.com

 

 

1) 프래그먼트 패키지 생성

 

프래그먼트를 보관할 패키지를 자바 폴더에 있는 com.example. 프로젝트명 파일에 생성한다

 

 

2) 프래그먼트 생성

블랭크 프래그먼트 3개를 방금 생성한 패키지에 생성한다 

주의 사항 

Include factory methods? 선택 해체

Include interface callbacks? 선택 해체

 

 

 

3)material 임포트 하기

projectStructure를 켠다

Ctrl+Shift+alt+s 단축키

 

1. 왼쪽 메뉴에서 Dependencies를 선택한다 

2. all Dependencies 아래 + 마크를 클릭한다

3. Library Dependancy를 클릭한다

 

material이라는 키워드로 검색 후

com.google.android.material을 선택하고

버전은 최신 버전을 선택한다

 

projectStructure의 장점은

빠르게 변화하는 안드로이드 메소드 덕분에

구 버전을 사용하면 생기는

오류들로부터 자유로울 수 있다

 

 

4) 메인 액티비티 레이아웃에 탭 레이아웃 추가

 

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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabTextColor="#ffffff"
        app:tabSelectedTextColor="#ffffff"
        android:background="@color/colorPrimaryDark"
        />
 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view_pager"
/>
 
</LinearLayout>
 
 

 

ConstraintLayout을 Linearlayout  방향 vertical

로 변경하고 탭 레이아웃과 뷰 페이저를 추가한다.

여기서 뷰 페이저의 역할은

프래그먼트들을 가로로 이어 붙여주고

탭 레이아웃에서 선택하면

선택된 프래그먼트로 이동하는데 부드럽게 넘어가는 모션이

추가된다 축측하고 있습니다.

 

이어서 자바 파일에 

탭 레이아웃과 뷰 페이저를 선언한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.example.test_tablayout;
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.view_pager);
    }
}
 
 
 

 

 

 

이어서 자바 폴더에 뷰 페이저 어뎁터 클래스를 생성한다.

 

extends FragmentPagerAdapter 부모 클래스를 추가한다.

재목에 빨간 줄이 생기는데, Alt+Enter를 클릭하면

필요한 메서드들을 자동적으로 추가하는 기능이 있다.

나머지는 밑의 코드를 참고하여 추가하면된다.

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
package com.example.test_tablayout;
 
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
 
 
public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> fragmentListTitle = new ArrayList<>();
 
    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }
 
    @NonNull
    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
 
    @Override
    public int getCount() {
        return fragmentListTitle.size();
    }
 
    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return fragmentListTitle.get(position);
    }
 
    public void AddFragment(Fragment fragment, String Title){
        fragmentList.add(fragment);
        fragmentListTitle.add(Title);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

AddFragment는 뷰 페이저에 프래그먼트와 이름을 같이 추가하기 위해 생성된 메서드이다.

 

 

5) 자바 코드로 돌아와서 뷰 페이저 어뎁터 설정을 해준다.

 

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
package com.example.test_tablayout;
 
 
 
import com.example.test_tablayout.Fragments.BlankFragment;
import com.example.test_tablayout.Fragments.BlankFragment2;
import com.example.test_tablayout.Fragments.BlankFragment3;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        TabLayout tabLayout = findViewById(R.id.tab_layout);
        ViewPager viewPager = findViewById(R.id.view_pager);
        
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.AddFragment(new BlankFragment(), "First Fmt");
        viewPagerAdapter.AddFragment(new BlankFragment2(), "Second Fmt");
        viewPagerAdapter.AddFragment(new BlankFragment3(), "Third Fmt");
        
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

뷰 페이저 어뎁터를 생성하고

프래그먼트와 타이틀 정보를 입력한다.

 

그리고 뷰 페이저에 뷰페이저 어댑터를 넣는다.

그리고 탭 레이아웃에 뷰 페이저를 넣는다.

 

6) 프레그먼트들의 레이아웃에 자기 이름 입력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".Fragments.BlankFragment">
 
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="fragment1" />
 
</FrameLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

나머지 2와 3도 설정하십시오

 

결과 확인

 

소스코드는 깃허브에 있습니다.

https://github.com/3210439/test_tablayout

 

3210439/test_tablayout

Contribute to 3210439/test_tablayout development by creating an account on GitHub.

github.com

 

참조한 자료

https://youtu.be/PJWBnkWudEI

 

1) 프로젝트 생성

 

 

2) res> menu directory 생성

 

 

3) menu 폴더에 xml 파일 생성

 

4) 메뉴 xml 파일 코드 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    <item
        android:title="첫 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/first_opt"/>
    <item
        android:title="두 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/second_opt"/>
    <item
        android:title="세 번째"
        android:icon="@drawable/ic_launcher_background"
        android:id="@+id/third_opt"/>
</menu>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

여기서 아이템 설정에 android:showAsAction="ifRoom" 을 하게 되면 

만약, 툴바(앱바)에 아이콘이 표시될 공간이 있다면 표시해주게 된다.

 

onCreateOptionsMenu 오버라이드 하기

1
2
3
4
5
6
7
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mymenu,menu);
        return true;
    }
 

 

inflater를 통해 메뉴를 풍선에 바람 넣어 형태를 만들듯 툴바에 메뉴 아이콘이 생기고

클릭하게 되면 메뉴가 표시된다.

 

 

6) onOptionsItemSelected

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.first_opt:
                Toast.makeText(getApplicationContext(), "첫번째", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.second_opt:
                Toast.makeText(getApplicationContext(), "두번째", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.third_opt:
                Toast.makeText(getApplicationContext(), "새번째", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
   }

 

결과 확인

 

 

아이템을 클릭하게 되면 토스트 메시지가 출력되게 된다.

 

 

 

소스코드는 깃허브에서 다운 가능합니다.

https://github.com/3210439/toolbar_test

 

3210439/toolbar_test

Contribute to 3210439/toolbar_test development by creating an account on GitHub.

github.com

 

+ Recent posts