차근차근/Android

[ study ] 다이어리 어플 만들어보기 2 - 부가설명4

예쁜꽃이피었으면 2015. 5. 6. 10:37

액티비티 호출방법 2

1. startActivity

- 단순히 호출한 Activity를 호출하는 Method

- 일방적 연계성만을 가지고 있는 경우, 결과를 return받을 필요가 없는 경우


2. startActivityForResult

- Activity호출에 따라 수행된 결과를 리턴해야 할 경우

- 쌍방간의 연계성이 있는 경우에 사용





SimpleCursorAdapter

[Android] SimpleCursorAdapter를 이용한 CustomListView 만들기

http://roter.tistory.com/173


내가 참고한 소스코드부분에서 몰라서 찾아봤는데 위의 블로그에 알맞은 설명이 있다.


Cursor cursor = dbHelper.readData();

String[] from = new String[]{dbHelper.DIARY_TABLE_COLUMN_NUMBER,dbHelper.DIARY_TABLE_COLUMN_TITLE,dbHelper.DIARY_TABLE_COLUMN_CONTENT}; //가져올 DB의 필드 이름

int[] to = new int[] {R.id.tv_diary_id,R.id.tv_diary_title,R.id.tv_diary_content}; //xml의 TextView의 id

SimpleCursorAdapter adapter = new SimpleCursorAdapter(

MainActivity.this, //ListView의 context ?

R.layout.row_item,//ListView의 Custom layout

cursor, //Item으로 사용할 DB의 Cursor

from,//DB 필드 이름

to);//DB필드에 대응되는 xml 

adapter.notifyDataSetChanged();

listview.setAdapter(adapter); //어댑터 등록






notifyDataSetChanged


http://www.androidpub.com/228404

notifyDataSetChanged API 가 호출되면 UI 의 변화가 생기기 때문에, notifyDataSetChanged 는 반드시 UI 스레드 (혹은 다른 말로 메인 스레드) 에서 호출되어야 합니다. Service 에서 그냥 호출하시면 안되고, Service 에 콜백함수를 등록시키신 후에, 해당 콜백이 호출되면, 메인 스레드로 post 하시거나 메인스레드와 연결된 Handler 에 메세지를 보내는 식으로 구현하셔야 할 듯 하네요.





http://www.androidpub.com/29788



ApiDemos -> View -> List -> 8. Photo list


        public void clearPhotos() {

            //mPhotos.clear();

            mPhotos.remove(mPhotos.size() / 2);

            notifyDataSetChanged();

        }


이렇게 수정하고 테스트 했습니다.


잘 작동합니다.


1. DATA수정 

2. notifyDataSetChanged()





http://www.androidstudy.co.kr/bbs/board.php?bo_table=C09&wr_id=26

예제소스도 올라와있음 가입하면 볼 수 있는듯.



<registerDataSetObserver()는 단순히 notifyDataSetInvalidated() 밑에 설명이 없다는것을 보여드리기 위한 것입니다.>


위에 보시면 ListView를 갱신하게 하는 메서드인 
notifyDataSetChanged(), notifyDataSetInvalidated() 2개가 있습니다.
(줄여서 SetChanged(), SetInvalidated()로 사용하겠습니다.)

위에 SetChanged()의 경우 View(하나의 샐)가 새로운것이 붙여진 것에 대해서 자신(ListView)을 재갱신 한다 이런 뜻인데요.(영어에 약해서 대충 이렇게 해석했습니다.)
밑에 SetInvalidated()의 경우 밑에 해석이 없습니다.(Document에서 가져 온것이기에 확인해보시면 진짜 나와있지 않는것을 확인하실 수 있습니다.)
해석이 없다는 말은 위의 것과 기능이 같거나 또는 설명을 자세히 적지 않겠다라는 의미인거 같은데요.

제가 해보면서 두 메서드의 차이점 
SetChanged()의 경우 ListView를 밑으로 쭉 내려 놓고 메서드를 호출하면 List가 갱신이 되면서 밑으로 내려 놓은 자리에 그대로 위치하여 화면이 보이게 됩니다.

하지만 
SetInvalidated()의 경우 ListView의 보이는 위치를 어디로 해놓아도 메서드를 호출하면 List가 갱신이 되고, List의 맨윗부분에(List의 첫번째 Index에) 화면이 보이게 됩니다.




http://stackoverflow.com/questions/2406937/android-save-checkbox-state-in-listview-with-cursor-adapter


I had the same issue myself: how to toggle multiple select CheckedTextView in a custom layout (i.e not using android.R.layout.simple_list_item_multiple_choice)

The following worked for me. The example I have is a custom view that is provided an adaptor extended from SimpleCursorAdapter.

My custom view (row_contact.xml):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_height="wrap_content" android:layout_width="fill_parent">

  <CheckedTextView
    android:id="@android:id/text1"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:gravity="center_vertical"
    android:paddingLeft="6dip"
    android:paddingRight="6dip" 
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    />

  <TextView
    android:text="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvNumber"
    android:layout_gravity="bottom" 
    android:paddingLeft="6dip"
    android:paddingRight="6dip" 
    />

</FrameLayout>

The adaptor is created in ListActivity.OnCreate, which calls setupViews():

  private void setupViews() {
    bOk       = (Button) findViewById(R.id.ButtonOK);
    bCancel   = (Button) findViewById(R.id.ButtonCancel);
    FListView = getListView(); 
    //
    bOk.setText("Select");
    //
    FListView.setItemsCanFocus(false);
    FListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    //
    bOk.setOnClickListener(this);
    bCancel.setOnClickListener(this);
    //
    ContentResolver content = getContentResolver();
    Cursor cursor = ApplicationHelper.MobilePhoneContacts(content);
    startManagingCursor(cursor);

    ListAdapter adapter = new CheckedCursorAdapter( SelectContacts.this, R.layout.row_contact, cursor,                
        new String[] {People.NAME, People.NUMBER},               
        new int[] {android.R.id.text1, R.id.tvNumber});          
    setListAdapter(adapter);
  }

The Custom adaptor:

  public class CheckedCursorAdapter extends SimpleCursorAdapter {

    Activity context;
    Cursor c;

    public CheckedCursorAdapter(Activity context, int rowContact, Cursor cursor, String[] strings, int[] is) {
      super(context, rowContact, cursor, strings, is);
      this.context = context;
      this.c = cursor;

    }

    public View getView(int position, View convertView, ViewGroup parent) {
      View row = convertView;
      ContactRowWrapper wrapper;

      if (row == null) {
        LayoutInflater inflater=context.getLayoutInflater();
        row = inflater.inflate(R.layout.row_contact, null);
        //
        wrapper = new ContactRowWrapper(row);
        row.setTag(wrapper);
      } else {
        wrapper = (ContactRowWrapper)row.getTag();
      }
      c.moveToPosition(position);
      wrapper.getTextView().setText( c.getString(c.getColumnIndex(Contacts.People.NUMBER)) );
      wrapper.getcheckBox().setText( c.getString(c.getColumnIndex(Contacts.People.NAME)) );
      wrapper.getcheckBox().setChecked(getListView().isItemChecked(position));
      //
      return row;
    }

  }

The crucial bit of code for for me was to get check boxes working was:

wrapper.getcheckBox().setChecked(getListView().isItemChecked(position));

Hope this helps you or anyone else who stumbles onto this question.

Also, pardon my Java noobness... I've only started Java a few weeks ago

반응형