[안드로이드 앱 개발] 5.위젯의 속성을 변경해보자
by 습작 | 13.10.28 01:25 | 4,755 hit
C++ 프로그램 개발자라면 윈도우 다이얼로그에서 특정 컨트롤을 수정하려면 먼저 해당 아이템을 GetDlgItem 함수를 통해 찾고 그 다음에 해당 컨트롤의 상태를 바꾸거나 텍스트를 변경하는 작업을 한다. 안드로이드에서도 findViewById 함수를 통해 해당 컨트롤에 접근하기 위한 클래스 정보를 얻고, 획득한 클래스 정보에 기반하여 컨트롤의 다양한 속성을 변경한다.

findViewById로 검색하기 위해서는 GLE(Graphical Layout Editor)에서 레이아웃이나 컨트롤에 Assign ID로 ID를 할당하거나, Edit ID로 원하는 ID를 부여해야한다. 
위의 그림을 보면 새로 추가한 LinearLayout이 기본적으로는  ID가 부여되지 않는데, 오른쪽 마우스 팝업 메뉴에서 Assign ID로 ID를 부여하면 레이아웃에 대한 속성을 어플의 실행중에 수정할 수 있다.
뷰나 위젯들에 대한 ID 설정을 하고 파일을 저장해 놓으면 위의 그림과 같이 이클립스 액티비티 코드 수정시 R.id.까지 입력해도 연관된 id를 자동적으로 보여주어 손쉽게 선택할 수 있도록 돕는다.
또한 그림에도 나와 있지만 코딩중에 Ctrl+Space 키를 클릭하면 지금까지 입력한 단어로 시작하는 것을 보여주어 외우거나, 모두 입력하지 않아도 손쉽게 코딩할 수 있도록 한다.

속성을 변경하기 위해서는 먼저 클래스 정보를 찾아와야 하는데, 위의 그림과 같이 클래스명 인스턴스명 = (클래스명 캐스팅)findViewById(아이디);와 같이 사용하고 실제 속성을 변경할 때는 인스턴스명.함수명(속성값)의 형태로 사용한다. 특정 뷰 내부에 있는 컨트롤을 검색할 때는 뷰명.findViewById()와 같은 방식으로 사용한다.
아래의 코드는 텍스트 컨트롤, 편집창, 버튼을 쌍으로 좌우에 각각 두고 버튼을 클릭하면 편집창의 내용을 텍스트 컨트롤에 표시하는 예제이다.

        final TextView leftText = (TextView) findViewById(R.id.left_text);
        final TextView rightText = (TextView) findViewById(R.id.right_text);
        final EditText leftTextEdit = (EditText) findViewById(R.id.left_text_edit);
        final EditText rightTextEdit = (EditText) findViewById(R.id.right_text_edit);
        Button leftButton = (Button) findViewById(R.id.left_text_button);
        Button rightButton = (Button) findViewById(R.id.right_text_button);
        
        leftButton.setOnClickListener(new OnClickListener() <
            public void onClick(View v) <
                leftText.setText(leftTextEdit.getText());
            >
        >);
        rightButton.setOnClickListener(new OnClickListener() <
            public void onClick(View v) <
                rightText.setText(rightTextEdit.getText());
            >
        >);

클래스명은 android.widget  패키지에 속한 클래스들로 자주 사용하는 것들과 사용 예는 아래와 같다.
(참조링크 : http://developer.android.com/reference/android/widget/package-summary.html)

Button
       Button twoButtonsTitle = (Button) findViewById(R.id.two_buttons);
        twoButtonsTitle.setOnClickListener(new OnClickListener() <
            public void onClick(View v) <
                showDialog(DIALOG_YES_NO_MESSAGE);
            >
        >);
        
        Button radioButton = (Button) findViewById(R.id.radio_button);
        radioButton.setOnClickListener(new OnClickListener() <
            public void onClick(View v) <
                showDialog(DIALOG_SINGLE_CHOICE);
            >
        >);
        
        Button checkBox = (Button) findViewById(R.id.checkbox_button);
        checkBox.setOnClickListener(new OnClickListener() <
            public void onClick(View v) <
                showDialog(DIALOG_MULTIPLE_CHOICE);
            >
        >);

CheckBox
CheckBox enableCheckBox = (CheckBox) findViewById(R.id.sms_enable_receiver);
enableCheckBox.setChecked(pm.getComponentEnabledSetting(componentName) ==
                                  PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Chronometer
Chronometer mChronometer;
mChronometer = (Chronometer) findViewById(R.id.chronometer);
mChronometer.start();
mChronometer.stop();
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.setFormat("Formatted time (%s)");
mChronometer.setFormat(null);EditText
EditText mQueryPrefill;
EditText mQueryAppData;

mQueryPrefill = (EditText) findViewById(R.id.txt_query_prefill);
mQueryAppData = (EditText) findViewById(R.id.txt_query_appdata);

final String queryPrefill = mQueryPrefill.getText().toString();
final String queryAppDataString = mQueryAppData.getText().toString();

Gallery
SpinnerAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_gallery_item, c,
                new String[] , new int[] < android.R.id.text1 >);

Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(adapter);
GridView
SpinnerAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_gallery_item, c,
               new String[] , new int[] < android.R.id.text1 >);

Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(adapter);
ImageSwitcher
private ImageSwitcher mSwitcher;
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
ImageView
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setDrawingCacheEnabled(true);
imageView.setImageDrawable(wallpaperDrawable);
imageView.invalidate();
LinearLayout
LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
for (int i = 2; i < 64; i++) <
        TextView textView = new TextView(this);
        textView.setText("Text View " + i);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        );
    layout.addView(textView, p);

    Button buttonView = new Button(this);
    buttonView.setText("Button " + i);
    layout.addView(buttonView, p);
>
ListView
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, AutoComplete1.COUNTRIES));
MultiAutoCompleteTextView
ArrayAdapter adapter = new ArrayAdapter(this,
                                                    android.R.layout.simple_dropdown_item_1line, COUNTRIES);
MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.edit);
textView.setAdapter(adapter);
textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());ProgressBar
final ProgressBar progressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal);
setProgress(progressHorizontal.getProgress() * 100);
setSecondaryProgress(progressHorizontal.getSecondaryProgress() * 100);
QuickContactBadge
ContactListItemCache cache = new ContactListItemCache();
cache.nameView = (TextView) view.findViewById(R.id.name);
cache.photoView = (QuickContactBadge) view.findViewById(R.id.badge);
view.setTag(cache);
RadioButton
Button radioButton = (Button) findViewById(R.id.radio_button);
radioButton.setOnClickListener(new OnClickListener() <
    public void onClick(View v) <
        showDialog(DIALOG_SINGLE_CHOICE);
    >
>);
RadioGroup
RadioGroup mFillingGroup;
mFillingGroup = (RadioGroup) findViewById(R.id.filling_group);
mFillingGroup.check(whichFilling);
RatingBar
RatingBar mIndicatorRatingBar;
mIndicatorRatingBar = (RatingBar) findViewById(R.id.indicator_ratingbar);
if (mIndicatorRatingBar.getNumStars() != numStars) <
        mIndicatorRatingBar.setNumStars(numStars);
>SeekBar
SeekBar mSeekBar;
mSeekBar = (SeekBar)findViewById(R.id.seek);
mSeekBar.setOnSeekBarChangeListener(this);Spinner
        Spinner s1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(
                this, R.array.colors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(adapter);
        s1.setOnItemSelectedListener(
                new OnItemSelectedListener() <
                    public void onItemSelected(
                            AdapterView<?> parent, View view, int position, long id) <
                        showToast("Spinner1: position=" + position + " id=" + id);
                    >

                    public void onNothingSelected(AdapterView<?> parent) <
                        showToast("Spinner1: unselected");
                    >
                >);
TableLayout,TableRow        final TableLayout table = (TableLayout) findViewById(R.id.menu);
        Button button = (Button) findViewById(R.id.toggle);
        button.setOnClickListener(new Button.OnClickListener() <
            public void onClick(View v) <
                mStretch = !mStretch;
                table.setColumnStretchable(1, mStretch);
            >
        >);

        TableRow row = new TableRow(this);

        TextView label = new TextView(this);
        label.setText(R.string.table_layout_8_quit);
        label.setPadding(3, 3, 3, 3);

        TextView shortcut = new TextView(this);
        shortcut.setText(R.string.table_layout_8_ctrlq);
        shortcut.setPadding(3, 3, 3, 3);
        shortcut.setGravity(Gravity.RIGHT | Gravity.TOP);

        row.addView(label, new TableRow.LayoutParams(1));
        row.addView(shortcut, new TableRow.LayoutParams());

        table.addView(row, new TableLayout.LayoutParams());
TextSwitcher
private TextSwitcher mSwitcher;
mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);

Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
mSwitcher.setInAnimation(in);
mSwitcher.setOutAnimation(out);
TextView
TextView tv = (TextView)view.findViewById(R.id.message);
tv.setText("Hello! Text!");

Toast
Toast toast = new Toast(this);
toast.setView(view);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
ToggleButton
ToggleButton pushToTalkButton = (ToggleButton) findViewById(R.id.pushToTalk);
pushToTalkButton.setOnTouchListener(this);

VideoView
private VideoView mVideoView;
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoPath(path);
mVideoView.setMediaController(new MediaController(this));
mVideoView.requestFocus();
ViewFlipper
private ViewFlipper mFlipper;
mFlipper = ((ViewFlipper) this.findViewById(R.id.flipper));
mFlipper.startFlipping();
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_in));
mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_out));
추천 2

댓글 12

벽하거사 2013.11.14 16:50
감사합니다.
매우 유익한 내용이었습니다...
『유나아빠』 2013.11.01 11:54
좋은하루되세요~                
한여름날의꿈 2013.10.29 11:09
감사합니다 ㅎ
천방지축 2013.10.29 10:40
감사합니다....
사막의장미 2013.10.29 10:36
점점 중동어 같은것이 등장하는군요~
세계를품다 2013.10.29 08:13
감사5
Oollalla 2013.10.29 00:23
좋은 정보 감사합니다.      
라떼로주세요 2013.10.28 17:46
ㅎㅎㅎ 못알아듣는건 저만은 아니겠죠?
길태 2013.10.28 15:53
감사합니다~
서현서진서율아빠 2013.10.28 15:35
모든 사람들이 활용할 수 있는 자료를 주세요....
알람방구 2013.10.28 13:46
감사합니다.
뽀대 2013.10.28 13:42
암튼 좋은정보네요 ㅎㅎ

이거슨 꿀팁 다른 게시글

게시물 더보기

이거슨 꿀팁 인기 게시글

  1. 알뜰폰 쓸 때 인터넷과 결합하려면2,639
  2. 해외여행 갈 때 데이터로밍 간편하고 싸게 쓰…2,506
  3. 기프티콘은 컬쳐랜드 쿠폰거래소에서 이용하…2,392
  4. 클리오 루즈힐 블룸 다이아 립스틱 5종 홈쇼…2,493
  5. 데이터 10GB+1Mbps 무제한 6,500원부터 쓸수…2,353
  6. 3월 알뜰폰 가성비 평생요금제 2가지 6GB 6천…2,098
  7. 3Mbps 속도 데이터무제한 최저가 검색2,100
  8. 컬쳐랜드에 쿠폰거래소가 새롭게 생겼어요2,062
  9. 해외여행 데이터로밍 일본 태국 대만 최저가…2,042
  10. 아싸컴에서 천만원 이벤트 하는 거 찾았다2,011

2024.05.17 03:00 기준