0

I am trying to make a simple tabbed application with different ListViews and options. I would like to manage the relationship between tabs and MainActivity and the problem right now is I cannot make an addItem() function in a menu button, to add a new item to my ListView (inside a Fragment) in a tabbed application. I already searched a lot, and I found only about adding an item in a simple ListView (inside MainActivity) or add items not dynamically in a tabbed application.

So here it is the screen of my Tabbed Application and the ListView that I am trying to work with. Custom List View Application Picture

[1]: https://i.stack.imgur.com/Ze4eu.png

And here is my code: MainActivity.java

public class MainActivity extends AppCompatActivity {



private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

}

The Fragment with the CustomList, that I am trying to implement the menu button method action_add():

    public class Catalogo extends Fragment {
    ArrayList<CustomList> custom = null;
    ListView lv = null;
    ArrayAdapter adapter = null;
    ArrayList<CustomList> elementos = new ArrayList<CustomList>();

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.catalogo, container, false);
        ListView lv = rootView.findViewById(R.id.catalogoListView);

        custom = addItems();
        adapter = new CustomAdapter(this.getContext(), custom);
        lv.setAdapter(adapter);

        return rootView;
    }

    private ArrayList<CustomList> addItems(){
        CustomList custom = new CustomList("Banana", "4.0");
        elementos.add(custom);
        custom = new CustomList("Morango", "5.0");
        elementos.add(custom);
        return elementos;
    }

    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_add){
            AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
            //builder.setTitle("Adicionar novo item"); //THESE ARE NOT WORKING
            //final EditText input = new EditText(this); //THIS SHOULD BE 2 Text Fields
            //builder.setView(input);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //NEED TO IMPLEMENT HERE
                }
            });
            builder.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public static String preferredCase(String original, String price)
    {
        if (original.isEmpty())
            return original;

        return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
    }

}

My CustomItem Structure:

   public class CustomList {
    String name;
    String price;
    public CustomList(String name, String price) {
        this.name = name;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public String getPrice() {
        return price;
    }
}

And at the end, my CustomAdapter:

    public class CustomAdapter extends ArrayAdapter<CustomList> {
    private final Context context;
    private final ArrayList<CustomList> elementos;

    public CustomAdapter(Context context, ArrayList<CustomList> elementos){
        super(context, R.layout.modelolista, elementos);
        this.context = context;
        this.elementos = elementos;
    }
    public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.modelolista, parent, false);

        TextView nameItem =  rowView.findViewById(R.id.tvName);
        TextView priceItem =  rowView.findViewById(R.id.tvPrice);

        nameItem.setText(elementos.get(position).getName());
        priceItem.setText(elementos.get(position).getPrice());

        return rowView;
    }
}
Adonis
  • 4,670
  • 3
  • 37
  • 57
Luis Abdi
  • 139
  • 2
  • 6
  • Sorry but I didn't get it.. you want to add an item to a list by clicking a menu item and notifying the list of that add so it can show the updated list? – Pier Giorgio Misley Sep 05 '17 at 12:53
  • Yea you are right, add a item in the list by the menu item. The problem is.. I implement the list and the menu item in the MainActivity... but I cannot implement them in a Fragment. So, there are two options.. First, implement the CustomList and all Menu Buttons in the MainActivity, but then I dont know how to pass this "made Custom List" to the Fragment (in "catalogo" tab). Second is, implement everything inside the Fragment ("Catalogo" tab), but then, I cannot implement the button functions like the way I can in MainActivity. – Luis Abdi Sep 06 '17 at 02:32
  • ok got it, just to know: you see the "add" button only when the catalog fragment is shown or you always see it? – Pier Giorgio Misley Sep 06 '17 at 07:12
  • it's always, I made the add button inside the MenuLayout. However I am sorry that looks so confusing, So I am going to remake all of it and post it again. – Luis Abdi Sep 06 '17 at 11:37

2 Answers2

0

The best way to use activity's data in fragment is to create a interface in fragment and implement in activity class

    public class Catalogo extends Fragment {
    private CatalogFragmentInteface catalogInterface;
    //rest of your code

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.catalogo, container, false);
            catalogIntreface.catalogInterfaceFunction(rootView);
    }
@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof CatalogFragmentInterface) {
            catalogInterface = (CatalogFragmentInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement CatalogFragmentInterface");
        }
    }

    interface CatalogFragmentInterface {
        void catalogInterfaceFunction(View view);
    }
    }

And in your Activity class implement this interface

public class MainActivity extends AppCompatActivity implement Catalog.CatalogFragmentInterface{
@Overide
void catalogInterfaceFunction(View view) {
    //access your listview in fragment using view variable
}
}

In this way all your data and listview is present in same class. I hope this will help you now.

Tavinder Singh
  • 380
  • 1
  • 7
  • 17
0

First of all a suggestion: instead of calling your item CustomList, consider calling it CustomListItem. This way you will remember easily in the future that it is an item, not a list.

That said, you should implement an add page\dialog.

There are many ways for doing this.. the "best approach" (i think) will be creating a custom add dialog. So you will have to create a custom layout and give it as the view of your layout with something like this:

AlertDialog.Builder builder = new AlertDialog.Builder(activity);
LayoutInflater inflater = activity.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.my_custom_view, null);
builder.setView(dialogView);

Now you can simply implement all listners and stuffs here by getting items as Button byButton = (Button)dialogView.getItemById(R.id.mybutton);

For any info check this answer that might help you (there are many others).

Now what we miss is refreshing the listview, this I think is the simplest way:

You can save a reference of your custom Fragment in your Activity. Then add in your Fragment a method like AddItemToList(). Now when user clicks the "Add" button, you can call this method from your fragment reference and implement the method as below(+-):

CallBack (MainActivity)

//add this param
private MyFragment myFragment;

//when you show the fragment add this:
myFragment = myFragmentIstance;

//on the save of the dialog, add this:
//do all checks and create item
CustomListItem cli = new CustomListItem(editTextName.getText().toString(), editTextPrice.getText().toString());
myFragment.AddItemToList(cli);

AddItemToList (Fragment):

public void AddItemToList(CustomListItem cli){
  myCustomListItemList.Add(cli);
  myAdapterView.notifyDataSetChanged();
}

Something like this should work.. For any question or explaination I'm here. Good luck

Pier Giorgio Misley
  • 5,305
  • 4
  • 27
  • 66