메뉴 건너뛰기

조회 수 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
번호 제목 날짜 조회 수
177 [Android 2.3] SharePreference 2015.07.01 7051
176 [Android 2.3] spinner file 2015.07.01 7647
175 [Android] 퍼미션 권한체크(테드퍼미션) 2021.09.14 616
174 [DB] 서버/클라이언트 소켓 통신하기 2015.07.13 20567
173 [DB]Android - DB 연동 기술 정리 2015.07.13 13798
172 [안드로이드 강좌] 초보자들이 많이 하는 실수 file 2015.08.11 6833
171 [안드로이드] Activity에 대해서 file 2015.07.16 6767
170 [안드로이드] 레이아웃의 기본1 file 2015.07.16 6962
169 [안드로이드] 레이아웃의 기본2 file 2015.07.16 7071
168 [안드로이드] 리스트 뷰의 한 항목에 대한 컨텍스트 메뉴 만들기 file 2015.09.04 9080
167 [안드로이드] 버튼 이벤트 처리하기 file 2015.07.17 7029
166 [안드로이드] 뷰(View)에 여백넣기 file 2015.07.17 7230
165 [안드로이드] 뷰(View)의 너비와 높이 지정하기 file 2015.07.17 7140
164 [안드로이드] 빠르게 사용할수 있는 컨텍스트 메뉴 만들기 file 2015.09.03 6789
163 [안드로이드] 콘텍스트 메뉴 사용예제 file 2015.09.03 7345
162 [안드로이드] 팝업메뉴 사용법 file 2015.09.03 9391
161 [안드로이드] 페이스북 같은 슬라이드 메뉴 만들기 file 2015.07.21 8182
160 [안드로이드] 화면추가 버튼 리스너 file 2015.07.22 7681
159 [안드로이드스튜디오] 단축키 2015.07.02 7160
158 [하이브리드앱] userAgent를 이용해서 웹 / 앱 접속 구분하기 2021.09.30 1284
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved