I have a ListView and I want to run a function according to the clicked value on ListView for now i just want to know only how to get and toast the value I was trying to do it but don't know the proper code... please check my code.
public class SubCategory extends AppCompatActivity implements View.OnClickListener {
private ListView listView;
String buttonType;
ArrayAdapter adapter;
static final String[] FRUITS = new String[] { "Apple", "Avocado", "Banana"};
static final String[] NAMES = new String[] { "Sachin", "Brett", "Shane", "Zaheer"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_category);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
buttonType = bundle.getString("BUTTON_CLICKED");
}
if(buttonType != null && buttonType.equals("A")) {
adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, FRUITS);
} else if(buttonType != null && buttonType.equals("B")) {
adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, NAMES);
}
listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(adapter);
}
public void getList() {
Toast.makeText(listView.getContext(), Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.listview:
getList();
break;
}
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list.get(position).GET_INFORMATION(); //GET_INFORMATION will be the method in your POJO class
}
});
try this
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value="";
if(!TextUtils.isEmpty(buttonType) && buttonType.equals("A")) {
value=FRUITS[position];
} else if(!TextUtils.isEmpty(buttonType) && buttonType.equals("B")) {
value=NAMES[position];
}
// you can get value in "value"
showToast(value);
}
});
public void showToast(String value) {
Toast.makeText(this,value, Toast.LENGTH_LONG).show();
}
To add click listener to listview follow these steps
1.add click listener like this in oncreate method of the activity.
listView.setOnItemClickListener(this);
2.Implement OnItemClickListener in the activity.
public class Main2Activity extends AppCompatActivity implements AdapterView.OnItemClickListener {
3.Override the onItemClick method in the activity.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Call method here
}
Related
I have a drawer menu with 3 items (Restaurant, Movie, Food). They are basically 3 to do lists. Each list has its on fragment and in the view there is a way to add items to the list.
The restaurant list, the movie list ad the groceries list.
I need to be able to share that list (via any share-channel) by clicking the share icon that is in the toolbar.
This is my fragment where i populate the items list that i want to use when i click the share icon that is on the toolbar. Basically i need to pass "items" to the MainActivity and use it.
package com.example.mylists;
import android.content.Intent;
public class FoodFragment extends Fragment {
public FoodFragment() {
// Required empty public constructor
}
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "FoodFragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onCreateView ");
View view = inflater.inflate(R.layout.fragment_food, container, false);
lvItems = (ListView) view.findViewById(R.id.lvItems);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(view.getContext(),android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
if (items.isEmpty())
items.add("Dummy Item");
final EditText newTask = (EditText) view.findViewById(R.id.etNewItem);
Button btnAdd = (Button) view.findViewById(R.id.btnAddItem);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemText = newTask.getText().toString();
itemsAdapter.add(itemText);
newTask.setText("");
writeItems();
Log.i(TAG, "in on send data ");
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.i(TAG, "in on onViewCreated ");
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "in on onActivityCreated ");
super.onActivityCreated(savedInstanceState);
OnItemLongClickListener listener = new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
//Log.i(TAG, "in on onItemLongClick ");
//Toast.makeText( getActivity().getBaseContext() , "Long Clicked " , Toast.LENGTH_SHORT).show();
items.remove(position);
itemsAdapter.notifyDataSetChanged();
writeItems();
//return true;
return false;
}
};
lvItems.setOnItemLongClickListener(listener);
}
private void readItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getContext().getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should declare ArrayList<String> items in your MainActivity. Then create a public setter method for items.
public void setItems(ArrayList<String> items){
this.items = items;
}
Then you should call setItems() method in your fragment.
((MainActivity) getActivity()).setItems(items);
Interface for Callback
interface MyInterface {
void setItems(ArrayList<String> items);
}
In your activity:
class MyActivity {
ArrayList<String> items;
MyInterface itemsCallback = new MyInterface(){
#Override
void setItems(ArrayList<String> items){
this.items = items;
}
}
myFragment.setItemsCallback(itemsCallback);
}
And then in fragment
class MyFragment {
private MyInterface itemsCallback;
public void setItemsCallback(MyInterface itemsCallback){
this.itemsCallback = itemsCallback;
}
private void readItems(){
...
itemsCallback.setItems(items);
}
}
I guess it's better then public setter in MainActivity. Because, you know, it's like more SOLID code. In this case your Fragment doesnt hold reference to Activity and doesnt even know about it existence.
1.Define an interface , 2.Let your Activity implements the interface 3.use (interface)getActivity() to cast your Activity to that interface,then you can call the method in the interface to send your ArrayList "items"
I made a listview of my server that sends images to a smartphone and the code I have works up there, the result is this :
Now I want to do that when you click on an item in the list, see the complete image in another layout and only get this by using intents.
I do not understand how to pass parameters in the onItemClick method. Please if someone tells me the solution.
The code is this :
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ProgressDialog progressDialog;
ArrayList asuntos=new ArrayList();
ArrayList imagen=new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
listView=(ListView) findViewById(R.id.list);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
lista o=new lista();
o.obtenerAvisos();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
startActivity(intent);
}
});
}
public class lista {
public void obtenerAvisos() {
asuntos.clear();
imagen.clear();
String tag_string_req = "req_data";
progressDialog.setMessage("Conectando...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppURLs.URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
asuntos.add(jsonArray.getJSONObject(i).getString("asunto"));
imagen.add(jsonArray.getJSONObject(i).getString("publicacion"));
}
listView.setAdapter(new ImagenAdaptador(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data");
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
public class ImagenAdaptador extends BaseAdapter {
Context ctx;
LayoutInflater layoutInflater;
SmartImageView smartImageView;
TextView tvasunto;
public ImagenAdaptador(Context applicationContext) {
this.ctx=applicationContext;
layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return imagen.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
String urlfinal="http://192.168.43.45/xxxx/xxxxx/"+imagen.get(position).toString();
Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
smartImageView.setImageUrl(urlfinal, rect);
tvasunto.setText(asuntos.get(position).toString());
return viewGroup;
}
}
}
Note: Use these libraries:
com.mcxiaoke.volley:library:1.0.19
and
com.github.snowdream.android:smartimageview:0.0.2
In this case you don't need to , you already have access to "imagen arrayList" :
public static final string ARG_IMAGE_URL = "URL";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
intent.putExtras(ARG_IMAGE_URL, imagen.get(position))
startActivity(intent);
}
});
But you will have to think of a strategy to avoid reloading the image from the network that would be a waste of resources.
Okay thanks so are the lines . Although this method had to move to the getView ImagenAdaptador class method :
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
final String urlfinal="http://192.168.43.45/InfoTec/publicaciones/"+imagen.get(position).toString();
Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
smartImageView.setImageUrl(urlfinal, rect);
tvasunto.setText(asuntos.get(position).toString());
**listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
intent.putExtra("arg", urlfinal);
startActivity(intent);
}
});**
return viewGroup;
}
For taking the ArrayList where they were not sent anything, the image variable is processed in this method of ImagenAdaptador class. Everything seemed fine only now visualize the last picture but click on any of the others, always sends the photo of Heineken. What happens now?
Clicking on Spinner Item adding new data into RecyclerView without removing old ones.
Like, I have two Items in a Spinner : Appliances and Accessories.
By default, I am showing Appliances data into RecyclerView, but whenever I do tap on Accessories - It is showing Accessories data into RecyclerView, but below Appliances data, whereas I was expecting only Accessories data into RecyclerView
MainActivity.java:
public class MainActivity extends AppCompatActivity {
.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_screen);
.........
stringList = new ArrayList<String>();
stringList.add("Appliances");
stringList.add("Accessories");
ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_dropdown_item_1line,
stringList);
spinnerMenu.setAdapter(stringArrayAdapter);
......
initializeAdapter();
.....
spinnerMenu.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
presenter.loadAppliances();
break;
case 1:
presenter.loadAccessories();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
.......
}
public void initializeAdapter() {
categoryAdapter = new CategoryAdapter(this, new ArrayList<Category>());
mRecyclerView.setAdapter(categoryAdapter);
}
public void addMenu(List<Category> posts) {
categoryAdapter.addAllData(posts);
categoryAdapter.notifyDataSetChanged();
}
}
CategoryAdapter.java:
#Override
public int getItemCount() {
return posts.size();
}
public void setPosts(List<Categories> posts) {
this.posts = posts;
}
public void clearData() {
posts.clear();
}
public void addAllData(List<Categories> posts) {
this.posts.addAll(posts);
}
}
First clear your old ArrayList and than add data into Arraylist.
public void addMenu(List<Category> posts) {
categoryAdapter.addAllData(posts);
categoryAdapter.notifyDataSetChanged();
}
public void addAllData(List<Categories> posts) {
this.posts.clear();
this.posts.addAll(posts);
}
You need to reset the adapter when an item is selected. So try this:
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
initializeAdapter();
//after this the switch case
I would also recommend that you have a way to know the spinner Menu Position.
After the first menupresenter.loadAppliances(); have int positionSelected = 0;
then in the switch case,
switch position
case: 0
if(positionSelected != 0) {
initializeAdapter();
menupresenter.loadAppliances();
positionSelected = 0;
}...
case: 1
if(positionSelected != 1) {
initializeAdapter();
menupresenter.loadAccessories();
positionSelected = 1;
}...
This will ensure that you don't reset the recyclerView adapter unnecessarily. Like if appliaces data is being shown and the user, selects appliances again in the dropdown
I'm using a Spinner in a Fragment. When the activity is created, the spinner doesn't show anything. It has no item when I click on the spinner, but the items are shown correctly.
When I select on the item nothing happens even though I call a Toast message.
P.S. The items come from an ArrayList of String from a database.
This is the code of the fragment:
public class RegStudentFragment extends Fragment {
private Spinner uniSpinner;
private RegistrationStudent activity;
private ArrayList<String> listaUni;
private int pos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.regs_frag, container, false);
uniSpinner=(Spinner) view.findViewById(R.id.spinnerUni);
System.out.println("fvfebeer");
manageUSpinner();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (RegistrationStudent) activity;
}
#Override
public void onActivityCreated(Bundle savedInstancestate) {
super.onActivityCreated(savedInstancestate);
listaUni = new ArrayList<String>();
new RequestFtp().setParameters(activity, "univer.php", "spinnerUni", RegStudentFragment.this).execute();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity().getApplicationContext(), android.R.layout.simple_spinner_item, getListaUni());
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
uniSpinner.setAdapter(adapter);
uniSpinner.setPrompt("Seleziona tra le seguenti:");
}
private void manageUSpinner() {
uniSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(activity.getApplicationContext(),"you selected ",Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(activity.getApplicationContext(),"No select ",Toast.LENGTH_SHORT).show();
}
});
System.out.println("vvsvsvsvsvs");
}
public void numeroel(ArrayList<ObjDb> result) {
ObjDb res= result.get(0);
String str=res.get("num");
int num=Integer.parseInt(str);
//numUni=new String[num];
}
public void arrayU(ArrayList<ObjDb> result){
int i=0;
while(i<result.size()) {
ObjDb res = result.get(i);
String str=res.get("nome");
listaUni.add(str);
i++;
}
}
public ArrayList<String> getListaUni(){
return listaUni;
}
}
I'm new to Android programming and am trying to figure out how to go about this. I have a fragment that hosts inner tabs, one of them being a ListFragment. On the tabhost fragment I have a button that calls a DialogFragment. When "Yes" is clicked on that DialogFragment I need to refresh that ListFragment if it's currently active in order to show the item added onto the list.
What is the best way to go about this? I am thinking I should put an interface on the DialogFragment and then implement the listener on the Activity which would then call the refresh in the ListFragment. I would need to be able to pull the ListFragment's tag in order to determine if it's active, however and not sure how to do that.
I just started to learn programming a few months ago and this is my first post on this site. I searched for this answer and couldn't find anything. I apologize if my methods or formatting are wrong. Any tips are appreciated, thanks.
TabFragment:
public class Items extends Fragment implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, View.OnClickListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
static final String ARG_ID = "id";
static final String name = "name";
long id;
String itemName;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.tab_test);
Bundle args = getArguments();
long id = args.getLong(ARG_ID);
String itemName = args.getString(name);
View v = inflater.inflate(R.layout.item_tab, container, false);
mViewPager = (ViewPager) v.findViewById(R.id.pager);
// Tab Initialization
//initialiseTabHost
mTabHost = (TabHost) v.findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
List<Fragment> fragments = getFragments();
FragmentActivity context = getActivity();
this.AddTab(context, this.mTabHost, this.mTabHost.newTabSpec("ItemList").setIndicator("ItemList"));
mTabHost.setOnTabChangedListener(this);
// Fragments and ViewPager Initialization
pageAdapter = new MyPageAdapter(getChildFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(this);
if (savedInstanceState == null) {
}else {
int pos = savedInstanceState.getInt("tab");
mTabHost.setCurrentTab(pos);
}
Button addItemButton = (Button) v.findViewById(R.id.addItem);
addItemButton.setOnClickListener(this);
return v;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.addItem:
DialogFragment addItem = new AddItemDialogFragment();
Bundle itemArgs = getArguments();
addItem.setArguments(itemArgs);
addItem.show(getChildFragmentManager(), "addItem");
Toast.makeText(getActivity(), "Adding Item", Toast.LENGTH_LONG).show();
break;
}
}
// Method to add a TabHost
private static void AddTab(FragmentActivity activity, TabHost tabHost, FragmentTabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
Bundle args = getArguments();
long id = args.getLong("val");
ItemList f1 = ItemList.newinstance(id);
fList.add(f1);
return fList;
}
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
}
ListFragment within Tab:
public class ItemList extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
String DATABASE_TABLE;
String Query;
String Order;
String name;
MainActivity home;
View view;
public static MyListAdapter mAdapter;
private static Cursor c;
static ItemList newinstance(long rowId) {
ItemList itemList = new ItemList();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putLong("val", rowId);
//args.putString("name", itemName);
itemList.setArguments(args);
return itemList;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle args = getArguments();
int itemId= (int) args.getLong("val");
mAdapter = new MyListAdapter(getActivity(), R.layout.list_row, c, from, to);
setListAdapter(mAdapter);
setListShown(false);
getLoaderManager().initLoader(itemId, null, this);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// View progressBar = getView().findViewById(R.id.progressbar_loading);
// progressBar.setVisibility(View.VISIBLE);
return new RawCursorLoader(getActivity(), Query + Order);
}
// Called when a previously created loader has finished loading
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//View progressBar = getView().findViewById(R.id.progressbar_loading);
// progressBar.setVisibility(View.GONE);
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
mAdapter.swapCursor(data);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
// Called when a previously created loader is reset, making the data unavailable
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
mAdapter.swapCursor(null);
}
}
Dialog:
public class AddItemDialogFragment extends DialogFragment {
UpdateItemListener mListener;
public interface UpdateItemsListener {
public void onItemAdded();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (UpdateItemListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement UpdateItemListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Add " + itemName + "?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
postItem(ItemId);
mListener.onItemAdded();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I was able to figure it out, my brain just got stuck for a while.
The first problem was that I was using FragmentStatePagerAdapter which does not set tags when instantiating the fragments. I set it to this since FragmentPagerAdapter was being buggy and another thread recommending extending that class instead. I was able to get it working with FragmentPagerAdapter which sets a tag. I then call getTag() during the onAttach() method of the ItemList fragment and set the variable on the activity. I then have an interface on the AddItemDialogFragment when the item is added and a listener on the activity. The listener then calls:
ItemList itemList= (ItemList)
getSupportFragmentManager().findFragmentByTag("Items")
.getChildFragmentManager().findFragmentByTag("itemListTag");
if(itemList != null) {
itemList.listChange();
}