Refreshing parent fragment on PopupWindow.dismiss - android

I have a popupWindow that modifies a SQLight table that loads a spinner in the parent window. I would like to have the spinner in the parent window refreshed with the new values when I dismiss the PopupWindow. The code below shows my progress creating a listener that would detect the PopupWindow's dismissal. The listener that I have so far does not work. I think that I have missed something in structuring the listener. I've included the ShowPopup class as well as the fragment (Tab3Fragment) that is the parent to this window.
showPopup.java
public class showPopup extends PopupWindow{
Context m_context;
Button btnDismiss;
PopupWindow popup;
Tab3Fragment Tab3Fragment;
OnDismissListener listener;
public showPopup(Context context){
super(context);
m_context = context;//was commented out
setContentView(LayoutInflater.from(context).inflate(R.layout.popup_layout, null));
setHeight(LayoutParams.WRAP_CONTENT);
setWidth(LayoutParams.WRAP_CONTENT);
}
public void init(View v){
LayoutInflater inflater = (LayoutInflater)m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popUpView = inflater.inflate(R.layout.popup_layout, null, false);
final PopupWindow popup = new PopupWindow(popUpView, 600, 400, true);
popup.setContentView(popUpView);
popup.showAtLocation(v, Gravity.CENTER_HORIZONTAL, 0, 0);
btnDismiss = (Button) popUpView.findViewById(R.id.btndismissxml);
btnDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View anchor) {
popup.dismiss();
}
});
}
#Override
public void setOnDismissListener(OnDismissListener listener){
this.listener = listener;
}
}
Tab3Fragment.java
public class Tab3Fragment extends Fragment implements OnClickListener{
Context context;
Button btnPopup, btnSpinnerRefresh;
Spinner spinnerSpecies;
public static int iSpeciesPosition;
showPopup showPopup;
ArrayAdapter<String> arrayAdapterSpecies;
OnDismissListener dismissListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerGroup, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3_fragment, containerGroup, false);
btnPopup = (Button)v.findViewById(R.id.btnPopupxml);
btnPopup.setOnClickListener(this);
btnSpinnerRefresh = (Button)v.findViewById(R.id.btnSpinnerRefreshxml);
btnSpinnerRefresh.setOnClickListener(this);
spinnerSpecies = (Spinner) v.findViewById(R.id.spinnerSpeciesxml);
spinnerSpecies.setAdapter(arrayAdapterSpecies);
if(savedInstanceState != null){
iSpeciesPosition = savedInstanceState.getInt("speciesPosition_key");
populateTab3Fragment(v);
}else if(savedInstanceState == null){
populateTab3Fragment(v);
}
return v;
}
//#Override
public void onViewCreated(View v) {
populateTab3Fragment(v);
/******************************************************************************************************
Can setOnDismissListener be used outside of showPopup class to indicate that showPopup has dismissed?
******************************************************************************************************/
showPopup popup = new showPopup(context);
popup.setOnDismissListener(new OnDismissListener(){
#Override
public void onDismiss(){
Toast.makeText(getActivity().getApplicationContext(), "onDismiss() works.", Toast.LENGTH_LONG).show();
loadSpinnerData();
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPopupxml:
new showPopup(getActivity().getApplicationContext()).init(v);
break;
case R.id.btnSpinnerRefreshxml:
loadSpinnerData();//temporary workaround to refresh spinner...
break;
}
}
/**
* Function to load the spinner data from SQLite database
* */
public void loadSpinnerData() {
//omitted
}
public void populateTab3Fragment(View v){
loadSpinnerData();
}
}

Never got to the point where I could refresh the parent window directly on the child PopupWindow dismiss. The final solution (workaround) was to use fragmentmanager replace() after an onTouch event from the spinner only when a static flag (iSpeciesRefresh) had been set that indicated a modified SQL spinner lookup table.
public class dataCapture extends Fragment implements OnClickListener {
String szSpecies;
static public int iSpeciesRefresh = 1;
Spinner spinnerSpecies;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.data_capture, container, false);
...
spinnerSpecies = (Spinner) v.findViewById(R.id.spinnerSpeciesxml);
spinnerSpecies.setOnTouchListener(new View.OnTouchListener() {//refreshes fragment as needed...
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (iSpeciesRefresh == 1) {//this is application default
//do nothing
} else if (iSpeciesRefresh == 0) {//value is reset to "0" at SAVE, UPDATE, or DELETE in speciesPopupWindow.
refreshDataCapture();
iSpeciesRefresh = 1;
}
return false;
}
});
...
}
public void refreshDataCapture() {
Fragment currentFragment = (dataCapture) getFragmentManager().findFragmentByTag("data_capture");
if (currentFragment == null) {
currentFragment = new dataCapture();
} else if (currentFragment != null) {
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getFragmentManager().beginTransaction().replace(R.id.fragment_placeholder, new dataCapture(), "data_capture").addToBackStack(null).commit();
}
}

In your onCreateView and onViewCreated methods, you do btnPopup.setOnClickListener(this);, but then in your showPopup class' init() method, you overwrite your fragment as the listener and instead assign a new anonymous listener. My guess is that you need to rework how you assign your listener and make sure you don't overwrite it like that.
P.S. For maintainability's sake (and the sanity of other developers who look at your code), it's convention to name classes with upper camel case and they should not contain verbs. Something like MyCustomPopup would be better.

Related

Update or switch BottomSheetDialogFragment inflated view when recyclerView dataset is changed

I have a BottomSheetDialogFragment and inside onCreateView i am inflating 2 different views based on a condition. Now my 1st view contains a recyclerView and the condition on which i want to switch my views is that if the list is empty then inflate view 1 else inflate view 2. Now my problem is when my list data count becomes 0 i want to call the onCreateView again so that based on the condition my 2nd view would be inflated. But i don't know how am i supposed to do it or rather is this the right way to do it.
My Code -
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (this.documentCount > 0) {
View v = inflater.inflate(R.layout.bottom_sheet_layout_document_attachments_added, container, false);
documentArrayList = dataToRender.get(fieldPosition).getAttachments();
Button attachMore = (Button) v.findViewById(R.id.btn_attachMore);
if(documentCount == 5){
attachMore.getBackground().setAlpha(128);
}else{
attachMore.getBackground().setAlpha(255);
}
attachMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(documentCount == 5){
PageLoader.showToast(getResources().getString(R.string.document_limit_message));
}else{
pickDocuments();
}
}
catch (Exception e){
Sentry.captureException(e);
}
}
});
Button btnCloseDrawer = (Button) v.findViewById(R.id.btn_closeDrawer);
btnCloseDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
recyclerview_documents = v.findViewById(R.id.recyclerview_documents);
adapter_documents = new DocumentAdapter(this, documentArrayList, fieldPosition);
recyclerview_documents.setAdapter(adapter_documents);
recyclerview_documents.setLayoutManager(new LinearLayoutManager(mContext));
return v;
} else {
View v = inflater.inflate(R.layout.bottom_sheet_layout_document, container, false);
TextView txtview_attach = (TextView) v.findViewById(R.id.txtview_attach);
txtview_attach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
permissionManager.checkPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE, new PermissionManager.PermissionAskListener() {
#Override
public void onNeedPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE
}, REQUEST_EXTERNAL_STORAGE);
}
#Override
public void onPermissionPreviouslyDenied() {
showDocumentRational();
}
#Override
public void onPermissionPreviouslyDeniedWithNeverAskAgain() {
dialogForSettings(getResources().getString(R.string.permission_denied), getResources().getString(R.string.permission_denied_document_access_message));
}
#Override
public void onPermissionGranted() {
pickDocuments();
}
});
}
catch (Exception e){
Sentry.captureException(e);
}
}
});
return v;
}
}```
Can't use more then one views for one fragment, but you can create a fragment wrapper that depends on the conditions, will show or create the fragment you need with the view you need.
for example WrapperFragment checking list size and creating Fragment1, when list size changed Wrapper fragment removung from fragment manager Fragment1 and add Fragment2

Android Studio - Update RecyclerView from Dialog Fragment in Menu Item

Hey guys I really need your help. I've spent like 5 days trying to get my recyclerview to update only when the user presses OK on a dialogbox, that appears from the menu actionbar. I've tried every possible method I could think of, every method I've seen on stackoverflow, YouTube, etc. and none of them worked for me.
How do I get the recyclerview in a fragment to update after dialogbox closes? I know there are similar questions regarding updating the menu, and (recyclerviews with dialogfragments), but none of them have a combination.
Out of the countless attempts, the current code configuration posted below isn't causing any errors, however, the recyclerview remains blank. The closest attempt I had to finding a solution, was creating an adapter and setting up the recycler in onOptionsItemSelected. But obviously, it updates only when the user clicks the button, and the initial click would create a blank recyclerview.
Fragment:
(There's a lot of repeated commented code from different attempts)
public class ExerciseRoutine extends Fragment implements ExerciseRoutine_Dialog.RoutineDialogListener{
private String Routine_name, Routine_split;
private ArrayList<ExerciseRoutine_Information> Routine_information = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#Override
public void sendInput(String name, String split, RecyclerView.Adapter DialogAdapter) {
Routine_name = name;
Routine_split = split;
adapter = DialogAdapter;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exercise_routine_fragment, container, false);
//Report that this fragment would like to participate in populating the options menu by
//receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods.
//If true, the fragment has menu items to contribute.
setHasOptionsMenu(true);
recyclerView = view.findViewById(R.id.ExerciseRoutine_Recycler);
//BuildRecyclerView();
//recyclerView.setHasFixedSize(true); //If the Recyclerview is static
/*Routine_information.add(new ExerciseRoutine_Information(Routine_name, Routine_split));
recyclerView = view.findViewById(R.id.ExerciseRoutine_Recycler);
//recyclerView.setHasFixedSize(true); //If the Recyclerview is static
layoutManager = new LinearLayoutManager(getActivity());
adapter = new ExerciseRoutineAdapter(Routine_information);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);*/
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.exercise_routine_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_addRoutine:
ExerciseRoutine_Dialog routineDialog = new ExerciseRoutine_Dialog();
routineDialog.setTargetFragment(ExerciseRoutine.this, 1);
routineDialog.show(getFragmentManager(), "Routine Dialog");
//Routine_information.add(new ExerciseRoutine_Information(Routine_name, Routine_split));
BuildRecyclerView();
//adapter.notifyItemInserted(Routine_information.size());
//if(!Routine_name.equals("") && !Routine_split.equals("")) {
//}
}
return super.onOptionsItemSelected(item);
}
public void BuildRecyclerView(){
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
public void BuildAdapter(){
//adapter = new ExerciseRoutineAdapter(getContext(),Routine_information);
adapter.notifyItemInserted(Routine_information.size());
}
}
My Dialog Fragment:
public class ExerciseRoutine_Dialog extends DialogFragment{
private TextView ActionOK, ActionCANCEL;
private EditText Routine_name, Routine_split;
private RoutineDialogListener activityCommander;
private ArrayList<ExerciseRoutine_Information> Routine_information = new ArrayList<>();
private RecyclerView.Adapter adapter;
public interface RoutineDialogListener{
void sendInput(String name, String split, RecyclerView.Adapter DialogAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (RoutineDialogListener) getTargetFragment();
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "Must Implement RoutineDialogListener");
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exercise_routine_dialog, container, false);
Routine_name = view.findViewById(R.id.ExerciseRoutine_DialogNameInput);
Routine_split = view.findViewById(R.id.ExerciseRoutine_DialogSplitInput);
ActionOK = view.findViewById(R.id.ExerciseRoutine_DialogAction_OK);
ActionCANCEL = view.findViewById(R.id.ExerciseRoutine_DialogAction_CANCEL);
//recyclerView = view.findViewById(R.id.ExerciseRoutine_Recycler);
ActionCANCEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getDialog().dismiss();
}
});
ActionOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = Routine_name.getText().toString();
String split = Routine_split.getText().toString();
if(!name.equals("") && !split.equals("")) {
Routine_information.add(new ExerciseRoutine_Information(name, split));
adapter = new ExerciseRoutineAdapter(getContext(), Routine_information);
activityCommander.sendInput(name, split, adapter);
adapter.notifyItemInserted(Routine_information.size());
}
getDialog().dismiss();
}
});
return view;
}
}
Your current approach seems to be to pass the RecyclerView.Adapter to the DialogFragment and try to insert the new data on-the-spot. I think this is a problematic setup. The dialog's purpose is to offer some means for the users to enter the required data, period. It should not be tasked with the job of managing the RecyclerView or its Adapter because that way your components will be very tightly coupled:
Imagine that first you use a ListView in your implementation, and suddenly someone decides to ban every ListView from your app (maybe for performance reasons) and has you exchange them all for RecyclerViews. Then your approach would force you to change the code for the DialogFragment (it would have to cater to a different type of Adapter). A more loosely coupled implementation would enable you to make changes to one component without having to rewrite too many others.
That's why I won't try to make your code work as-is, instead I'd like to show you another way:
Because the RecyclerView is part of the Fragment's UI, the Fragment is the place where code related to managing the RecyclerView belongs. It is basically possible to have the Adapter as an inner class of the Fragment but I prefer having it as a standalone class if the code gets a little longer, and also because it enforces "decoupling".
Interfaces play a very important part in good architecture, so the DialogFragment will still make use of an interface to send its data. But it's up to the class which actually implements the interface (here: the Fragment) to pass the data to any interested third parties, e.g. the RecyclerView.Adapter (The Adapter in turn could have its own interface to publish important events like clicks on list items).
Having said that, here are some code snippets:
The DialogFragment
public class ExerciseRoutine_Dialog extends DialogFragment {
private EditText Routine_name, Routine_split;
public interface RoutineDialogListener{
/**
* There is some new ExerciseRoutine_Information
*/
void sendInput(String name, String split);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exercise_routine_dialog, container, false);
Routine_name = view.findViewById(R.id.ExerciseRoutine_DialogNameInput);
Routine_split = view.findViewById(R.id.ExerciseRoutine_DialogSplitInput);
TextView actionOK = view.findViewById(R.id.ExerciseRoutine_DialogAction_OK);
TextView actionCANCEL = view.findViewById(R.id.ExerciseRoutine_DialogAction_CANCEL);
actionCANCEL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getDialog().dismiss();
}
});
actionOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = Routine_name.getText().toString();
String split = Routine_split.getText().toString();
if(!name.equals("") && !split.equals("")) {
// just send the input to the main Fragment
RoutineDialogListener listener = getListener();
if(listener != null) {
listener.sendInput(name, split);
}
}
getDialog().dismiss();
}
});
return view;
}
/**
* Tries to find a suitable listener, examining first the hosting Fragment (if any) and then the Activity.
* Will return null if this fails
* #return x
*/
private RoutineDialogListener getListener(){
RoutineDialogListener listener;
try{
Fragment onInputSelected_Fragment = getTargetFragment();
if (onInputSelected_Fragment != null){
listener = (RoutineDialogListener) onInputSelected_Fragment;
}
else {
Activity onInputSelected_Activity = getActivity();
listener = (RoutineDialogListener) onInputSelected_Activity;
}
return listener;
}catch(ClassCastException e){
Log.e("Custom Dialog", "onAttach: ClassCastException: " + e.getMessage());
}
return null;
}
}
The Fragment:
public class ExerciseRoutine extends Fragment implements ExerciseRoutine_Dialog.RoutineDialogListener{
public static final String ROUTINE_DIALOG = "Routine Dialog";
private ArrayList<ExerciseRoutine_Information> routineInformations = new ArrayList<>();
private RecyclerView.Adapter adapter;
public static ExerciseRoutine instance(){
return new ExerciseRoutine();
}
#Override
public void sendInput(String name, String split) {
routineInformations.add(new ExerciseRoutine_Information(name, split));
adapter.notifyItemInserted(routineInformations.size());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.exercise_routine_fragment, container, false);
setHasOptionsMenu(true);
RecyclerView recyclerView = view.findViewById(R.id.ExerciseRoutine_Recycler);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new ExerciseRoutineAdapter(getContext(), routineInformations);
// So far you have a RecyclerView with an empty List.
recyclerView.setAdapter(adapter);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.exercise_routine_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_addRoutine:
showDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showDialog(){
ExerciseRoutine_Dialog routineDialog = new ExerciseRoutine_Dialog();
routineDialog.setTargetFragment(ExerciseRoutine.this, 1);
routineDialog.show(getFragmentManager(), ROUTINE_DIALOG);
}
}

Recycler view does not update the list item dynamically after adding an item from another fragment

I have three fragments. One fragment shows the recycler view list items, another fragment opens up a dialog fragment which is sort of a form. It takes data and adds to the list. Now here after adding the list item the list should get updated as it's default behaviour, but it is not getting updated. But when I open activity after closing then it comes. What should be the problem can anyone tell me or can provide some sort of reference to consult. Thank you.
public class MyDialogFragment extends DialogFragment implements TextView.OnEditorActionListener {
List<CardListDataClass> listDataClasses = new ArrayList<>();
Fragment fragment;
FragmentTransaction ft;
List<CardListDataClass> list;
UserNameListener userNameListener;
private EditText mEditText, mEditText1, mEditText2;
// Empty constructor required for DialogFragment
public MyDialogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_item_layout, container);
mEditText = (EditText) view.findViewById(R.id.detailEdit);
mEditText1 = (EditText) view.findViewById(R.id.expEdit);
mEditText2 = (EditText) view.findViewById(R.id.expExtra);
CardView submit = (CardView) view.findViewById(R.id.submitDetail);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String det, exp, extra;
det = mEditText.getText().toString();
exp = mEditText1.getText().toString();
extra = mEditText2.getText().toString();
createDb createDb = new createDb(view.getContext());
createDb.dbopen();
createDb.createEntry(det, exp);
createDb.close();
listDataClasses.add(new CardListDataClass(det, exp));
getDialog().dismiss();
}
});
// set this instance as callback for editor action
mEditText.setOnEditorActionListener(this);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
getDialog().setTitle("Please enter details");
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
userNameListener = (UserNameListener) getActivity();
} catch (ClassCastException c) {
Log.e("ClassCastException", "yeah");
}
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Return input text to activity
userNameListener.onFinishUserDialog(mEditText.getText().toString(), mEditText1.getText().toString());
this.dismiss();
return true;
}
public interface UserNameListener {
void onFinishUserDialog(String detail, String exp);
}
This is the dialog fragment from where the list is to be updated in another fragment.
Hello everyone thank u for your concern. My problem is solved now. I was referencing another new object of list for adding the item. So the item was not being added there itself.
But I have an another problem here, where I am adding the item by specifying the position item is not added dynamically, i.e.
list.add(position,new item(a,b))

Cannot update views on left and right side of view pager

I have used viewpager which displays view with an image and radiobutton below. Each swipe screen is not a fragment, they are layouts which just swipe the same view with different imageview. The problem is that, I am unable to deselect the radio button which is in left and right side of the current view after i select the radio button of the current screen. If I return POSITION_NONE in getItemPosition(), it refresh the screen and radio button also deselected but the view is flickered. If i am able to call instantiateItem(), my problem is solved . But this method is called only when view is destroyed based on the setOffsetScreenPageLimit(). How can I achieved such requirements, if view pager cannot help?
Fragment:
public class AnswerImageDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
//member declaration
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strQuestion = null;
View rootView = inflater.inflate(R.layout.activity_viewpager_demo, container,
false);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
intro_images = (ViewPager) rootView.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) rootView.findViewById(R.id.viewPagerCountDots);
//do some stuff
//set the adapter
mAdapter = new ViewPagerAdapter(getContext(), map);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(clickPosition);
intro_images.setOnPageChangeListener(this);
setUiPageViewController();
bus = EventBus.getDefault();
bus.register(this);
return rootView;
}
//other method
}
PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// member declaration
public ViewPagerAdapter(Context mContext, HashMap<String, Object> map) {
//other initialization
}
#Override
public int getCount() {
return optionImages.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);
final ImageView ivOption = (ImageView) itemView.findViewById(R.id.answerId); // this is used as radio button in this case
/*The code snippet is to select the answer option based on whether answer is choosen or not.
If choosen, select as default in the pop up answer.
*/
if (null != ans) {
Iterator iterator = ans.iterator();
if (ans.size() > 0) {
int value = (int) iterator.next();
if (value == position) {
ivOption.setImageResource(R.drawable.ic_radio_button_tick);
} else {
ivOption.setImageResource(R.drawable.ic_radio_button_nontick);
}
}
}
p = position;
/*The code snippet is to change the answer value based on the user selection.
This means if user choosen another answer then clear the earlier choosen answer
*/
ivOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
txtQuestion.setText(question);
txtOption.setText(optionsList.get(position));
imageView.setParseFile(optionImages.get(position));
imageView.loadInBackground();
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
LinearLayout ll = (LinearLayout) object;
/*RelativeLayout ivOption = (RelativeLayout) ll.getChildAt(2);
ImageView iv = (ImageView) ivOption.getChildAt(1);
iv.setImageResource(R.drawable.ic_radio_button_tick);*/
container.removeView(ll);
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
public void refresh(ArrayList object) {
this.object = new ArrayList();
this.object.addAll(object);
this.notifyDataSetChanged();
}

Android Fragments Extra Code

I faced up a problem with my Android application. I'm a beginner and I tend to learn on my own. So I am trying to make a MediaPlayer and in order to do that, I need to use Fragments. The problem is not the Fragment itself but that I need to add some extra buttons with onClickListeners by the side of the MediaPlayer and my application is crashing because the fragment_main.xml file has the layout parameters but i cannot use the OnClickListener function in the Fragment(I get an error at findViewById(cannot make static reference to non-static method). Please help me.
public class MainActivity extends Activity {
Button blade;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
/* blade = (Button)findViewById(R.id.fantab);
blade.setOnClickListener(new OnClickListener(){
#Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent vent = new Intent(MainActivity.this, Ventscreen.class);
startActivity(vent);
finish();
}
});
*/
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
private static final String[] FROM = { MediaStore.Audio.Media.TITLE };
private static final int[] TO = { android.R.id.text1 };
private CursorAdapter mAdapter;
Button blade;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
return view;
blade = (Button)findViewById(R.id.fantab);
blade.setOnClickListener(new OnClickListener(){
#Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent vent = new Intent(MainActivity.this, Ventscreen.class);
startActivity(vent);
finish();
}
});
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Context context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Audio.Media.TITLE + " ASC");
int flags = 0;
mAdapter = new SimpleCursorAdapter(context, layout, cursor, FROM, TO, flags);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mAdapter.notifyDataSetChanged();
}
}
}
It is not just one button, the code above is just for example, there should be five buttons in total.
Thanks.
blade = (Button)findViewById(R.id.fantab);
You're trying to call the findViewById(int) method of the outer Activity. This is not possible, sincer your inner Fragment class is static. What you want to do is call findViewById(int) on the Fragment View:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
blade = (Button) view.findViewById(R.id.fantab);
blade.setOnClickListener(new OnClickListener(){
#Override
//On click function
public void onClick(View view) {
//Create the intent to start another activity
Intent vent = new Intent(getActivity(), Ventscreen.class);
getActivity().startActivity(vent);
getActivity().finish();
}
});
return view;
}
Also, note the placement of the return view; statement.

Categories

Resources