问题描述:

i got a problem here. As the title said, i want to update a listview in a fragment adding a value from an edittext of another fragment. My main activity is a navigation drawer. My fragment with the listview is the Fragment_hotels and the other fragment witch contains the edittext is the FragmentAddHotel. I want to add in the listview (with the hotels) a new hotel.

Can someone explain how to do that?

Code given below:

Fragment_hotels:

public class Fragment_hotels extends Fragment {

public static boolean flag=false;

public void Add(){

Target.add("Hotel");

Target.add("Hotel1");

Target.add("Hotel2");

}

static ArrayList<String> Target = new ArrayList<String>();

@Override

public View onCreateView(

LayoutInflater inflater,

ViewGroup container,

Bundle savedInstanceState){

View view = inflater.inflate(R.layout.fragment_hotels, container,false);

ListView listView = (ListView) view.findViewById(R.id.list);

if (flag==false){

this.Add();

}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),R.layout.mytextview,R.id.tv, Target);

adapter.setNotifyOnChange(true);

// Assign adapter to ListView

listView.setAdapter(adapter);

return view;

}

}

And FragmentAddHotel:

public class FragmentAddHotel extends Fragment {

public View onCreateView(

LayoutInflater inflater,

ViewGroup container,

Bundle savedInstanceState){

View rootView = inflater.inflate(R.layout.fragment_add_hotel, container, false);

return rootView;

}

}

I got an edittext and a button on my FragmentAddHotel layout.

How can i get the value from edittext and add it on the listview?

Sorry if a similar question has already been answered but i am junior programmer.

Tnx in advance :)

网友答案:

To update view in class from another one you can use EventBus library here is the link

Just register you first class by adding:

EventBus.getDefault().register(this); //in your listener class that contains the listview at onCreate method.

Also implement your receiver method:

public void onEventMainThread(String hotelName) {
   // Add the hotelName in your Target array list and then notify your adapter by adapter.notifyDataSetChanged(); 
}

To send data from your fragment just use :

EventBus.getDefault().post("edittextvalue");

Also don't forget to call :

EventBus.getDefault().unregister(this); // In your listener class onDestroy() method.

网友答案:

In YourActivity:

Fragment_hotels frag_hotels;

void addItem(String item){
  frag_hotels.addItemToList(item);
}

Fragment_hotels:

List<String> hotelList;
ArrayAdapter<String> adapter;
void addItemToList(String item){
   hotelList.add(item);
   adapter.notifyDataSetChanged();
}

In FragmentAddHotel:

// you should call whenever adding is need in fragment
((YourActivity)getActivity()).addItem("Your Item");

Through YourActivity, you can communicate each fragment.

相关阅读:
Top