메뉴 건너뛰기

조회 수 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 안드로이드 - RecyclerView 안에 RecyclerView 구현하기 file 2021.04.02 502
236 안드로이드 - Json 파싱하기 file 2021.04.02 828
235 안드로이드 - 타이머(Timer) 구현하기 2021.04.01 1368
234 안드로이드 - SQLiteDatabase 구현하기 file 2021.04.01 241
233 안드로이드 - 리사이클러 뷰(RecyclerView) 구현 file 2021.04.01 388
232 안드로이드 - 네비게이션 드로어(Navigation Drawer)를 활용하여 슬라이드 메뉴 구현하기 file 2021.04.01 1856
231 안드로이드 - 툴바(ToolBar)를 사용하여 앱바(App Bar) 구현하기 file 2021.04.01 454
230 안드로이드 - 프로그레스바(ProgressBar) 구현하기 file 2021.04.01 451
229 안드로이드 - AsyncTask 구현 예제 file 2021.04.01 280
228 안드로이드 - 액티비티(Activity)와 액티비티 생명 주기(Activity Life Cycle) file 2021.04.01 225
227 안드로이드 - 리스트뷰(ListView) 구현 file 2021.04.01 490
» 안드로이드 - 컨텍스트 메뉴(Context Menu) 사용 예제 file 2021.04.01 206
225 안드로이드 - 옵션 메뉴 (Option Menu) 구현 방법 file 2021.04.01 283
224 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
223 안드로이드 - 날짜 및 시간 정보 입력받기 (DatePickerDialog / TimePickerDialog) file 2021.04.01 1759
222 안드로이드 - setContentView()와 레이아웃 전개자(LayoutInflater) 2021.04.01 227
221 안드로이드 - AlertDialog 사용하여 알림창 띄우는 방법 총정리 file 2021.03.31 686
220 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 281
219 안드로이드 - 토스트(Toast) 메시지 사용하기. file 2021.03.31 321
218 안드로이드 - 액티비티(Activity)로부터 결과 데이터 받아오기 file 2021.03.31 483
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved