I’m developing an Android 3.1 application that uses fragments.
On one of those fragments a need to create n buttons and set an onClick event handler for each of them.
To do it I want to create a method on FragmentActivity that handles those events but I don’t know how. Note: FragmentActivity is a android.support.v4.app.FragmentActivity that manages all fragments using android.support.v4.view.ViewPager.
On another fragment I have the following XMLcode:
<Button
android:id="@+id/btnTakeArticlePhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="@string/btn_take_photo"
android:onClick="onTakePhotoClick" />
And this code on FragmentActivity:
public void onTakePhotoClick(View view)
{
Log.v("FillEReportFragmentActivity", "onTakeFactoryPhotoClick");
int imgType, imgSubType;
switch (view.getId())
{
case R.id.btnTakeFactoryPhotos:
imgType = ImageType.EREPORT;
imgSubType = SubImageType.EREPORT_FACTORY_OUTLOOK;
break;
case R.id.btnTakeArticlePhotos:
imgType = ImageType.ARTICLE;
imgSubType = SubImageType.NONSET;
default:
imgType = -1;
imgSubType = -1;
break;
}
Intent intent = new Intent(FillEReportFragmentActivity.this, CameraActivity.class);
intent.putExtra(BundleKeys.tablePk, eReportId);
intent.putExtra(BundleKeys.imgType, imgType);
intent.putExtra(BundleKeys.imgSubType, imgSubType);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
I want to do the same with these n buttons: create a method on FragmentActivity to handle all onClick events.
I see that if I want to handle onClick event on a button created programmatically I need to implement onClickEventListener.
How can I handle those onClick events on FragmentActivity? or is there a better approach?
You should make your
FragmentActivityimplementView.OnClickListener.Then in your
Fragmentin theonActivityCreated()callback you can do the following :You could also define your own
interfaceand make yourActivityimplement thatinterfaceand the same inonActivityCreated(), and let theFragmentimplementOnClickListenerand then call yourActivitylike this :