메뉴 건너뛰기

조회 수 206 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

1. 컨텍스트 메뉴(Context Menu) 구현 과정

컨텍스트 메뉴(Context Menu)를 구현하는 과정을 살펴보겠습니다. 컨텍스트 메뉴(Context Menu)는 특정 뷰(View)를 길게 눌렀을 때 활성화되는 메뉴입니다. 특정 뷰(View)가 컨텍스트 메뉴(Context Menu)가 동작하는 뷰(View)로 등록하기 위해서는 액티비티의 registerForContextMenu(View view) 함수를 사용합니다. 

 

 

View에 ContextMenu 등록하기

 

▼ 특정 뷰(View)에 Context Menu를 등록하기 위해서는 registerForContextMenu() 함수를 통하여 인자정보를 뷰(View) 객체를 넘겨줘야 합니다. 뷰(View) 객체는 findViewById(뷰 리소스 ID)를 통해 얻을수 있습니다. 

 

 

Context Menu 제어를 위한 3가지 재정의 함수

 

▼특정 뷰(View)에 대한 Context Menu의 동작을 제어하기 위해서는 위 그림에서 표시된 액티비티의 세 가지 재정의 함수를 사용합니다. onCreateContextMenu()는 Context Menu가 활성화될 때 가장 먼저 호출되는 함수로 Context Menu의 Menu Item을 생성하거나 추가하는 작업을 진행합니다.

이전 옵션 메뉴(Option Menu)의 onPrepareOptionsMenu()와 같은 함수가 따로 없기때문에 Context Menu가 활성화될 때마다 onCreateContextMenu()가 호출됩니다.

 

▼ ContextMenu가 활성화되고 사용자가 특정 MenuItem을 클릭하였을 때 onContextItemSelected() 함수가 호출됩니다. 위 함수에서는 사용자가 선택한 메뉴에 대한 처리를 진행하면 됩니다. 

 

▼ ConntextMenu가 활성화되고 사용자가 이전 버튼을 클릭하거나 화면상의 다른 뷰(View)에 포커스가 가는 경우에 onContextMenuClosed() 함수가 호출됩니다

 

2. 컨텍스트 메뉴(Context Menu) 예제 구현

예제는 TextView에 Context Menu를 등록하고 Menu를 통해 TextView의 Text 색상을 변경하는 간단한 예제입니다. 먼저 예제의 메인 화면 UI를 담당하는 XML 레이아웃 리소스입니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="해당 Text를 길게 클릭하세요"
        android:textAlignment="center"
        android:textSize="30sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

다음은 컨텍스트 메뉴(Context Menu)를 구성하는 XML 레이아웃 리소스입니다. 

해당 파일의 경로는 /res/menu/context_menu.xml 입니다.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/red"
        android:title="Red" />
    <item
        android:id="@+id/blue"
        android:title="Blue" />
    <item
        android:id="@+id/green"
        android:title="Green" />
</menu>

▼ 다음은 MainActivity를 실행하기 위한 자바 소스 코드입니다. 

public class MainActivity extends AppCompatActivity {

    private TextView textView;

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

        textView = (TextView) findViewById(R.id.textView);
        registerForContextMenu(textView);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu,
                                         View v,
                                         ContextMenu.ContextMenuInfo menuInfo)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }

    public boolean onContextItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.red:
                textView.setTextColor(Color.RED);
                return true;
            case R.id.blue:
                textView.setTextColor(Color.BLUE);
                return true;
            case R.id.green:
                textView.setTextColor(Color.GREEN);
                return true;
        }

        return super.onContextItemSelected(item);
    }
}

▼ onCreate() 함수에서는 TextView 객체를 받아와 registerForContextMenu() 함수를 통해서 해당 뷰(View)에 Context Menu를 등록합니다. 

 

▼onCreateContextMenu() 함수를 재정의하여 Inflater를 통해 Menu 리소스에 정의된 내용을 파싱 하여 컨텍스트 메뉴(Context Menu)를 생성합니다.

 

▼ onContextItemSelected() 함수를 재정의합니다. 선택 된 MenuItem에 따라 분기하여 TextView의 Text 색상을 지정해주고 있습니다.

 

 

 

 

예제 앱 실행 결과

 


List of Articles
번호 제목 날짜 조회 수
237 카카오톡 분석하기 (1) - sqlite 파해치기 file 2016.05.26 10452
236 카카오톡 대화내용 가져오기(sqlite3, chat_logs) file 2016.05.26 15125
235 초기화면 페이지를 만들어보자. splash 페이지 제작 file 2020.12.14 285
234 체크 박스(CheckBox)의 이미지 바꾸기 2015.07.16 6398
233 줄바꿈 문자 치환 2020.12.14 289
232 전화 인텐트와 나의 전화 번호가져오기 2014.08.28 6312
231 인텐트를 이용한 Activity간 데이터 전달 (사용자 정의 클래스) file 2015.07.16 7061
230 이미지의 Orientation를 체크해서 이미지 회전하기 2015.07.16 7658
229 이미지 버튼(ImageButton) 만들기 2015.07.16 7114
228 이미지 버튼 설정 2015.07.16 6378
227 위젯 업데이트 주기 빠르게 하기 2018.10.02 2142
226 월별 캘린더에 일정 입력 및 조회 기능 리스트로 추가하기 file 2015.07.16 18552
225 옵션 메뉴 동적으로 생성하기 2015.07.16 6926
224 어댑터 뷰(Adapter View) & 어댑터(Adapter) (1) file 2016.06.08 7852
223 앱 번들(Android App Bundle) 만들기 file 2021.09.14 305
222 암시적 인텐트를 사용한 인터넷열기, 전화걸기, 문자보내기 [Intent (인텐트)] file 2016.06.07 7736
221 알아놓으면 좋은 내용정리 2016.06.07 7458
220 안드로이트 비콘 스캐닝시 고려 사항 2015.07.26 6658
219 안드로이드용 채팅프로그램 클라이언트(java), 서버(c#) 소스 file 2016.05.19 11723
218 안드로이드와 mysql 연동시키기. php 와 json 사용 file 2015.07.16 24488
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved