- 인터페이스를 이용해서 프래그먼트에서 액티비티로 이벤트를 전달 하는 방법-  

[MainActivity]
public class MainActivity extends AppCompatActivity implements OnListItemSelectedListener{

private static String[] NUMBERS = new String[] { "1", "2", "3", "4", "5" };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// 프래그먼트 생성

ArrayListFragment list = new ArrayListFragment();

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(android.R.id.content, list).commit();
}

public void onListItemSelected(String itemName) {
setTitle(getTitle() + " " + itemName);
}

public static class ArrayListFragment extends ListFragment {
OnListItemSelectedListener myListener;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);

try {
// activity OnListItemSelectedListener 인터페이스가 구현되어 있어야 캐스팅 가능함.
myListener = (OnListItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnListItemSelectedListener interface");
}
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, NUMBERS));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

getListView().setItemChecked(position, true);

// 프래그먼트 아이템 클릭시 인터페이스 함수 호출하여 전달
myListener.onListItemSelected(NUMBERS[position]);
}
}
}

 
[OnListItemSelectedListener.java] // 인터페이스
public interface OnListItemSelectedListener {
public void onListItemSelected(String itemName);
}
 


+ Recent posts