我有两个片段和一个主要活动。第一个片段ContactListFragment是联系人列表,第二个片段ContactFragment收集联系人信息,然后将该信息发送回MainActivity,再次发送给ContactListFragment。单击ContactFragment中的“添加联系人”按钮时,应再次加载第一个片段,并显示更新的联系人列表。 onClick正在工作,我有一个显示的Toast消息,并且我的mCallback中有信息,但是当我点击“Add Contact”时我的第一个片段没有再次加载。我是碎片的新手,但是从我看到的所有代码中我认为我已正确连线。所以你不必去挖掘它,这是我的onClick中的相关代码...
OnSubmitListener mCallback = new OnSubmitListener() {
@Override
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable) {
}
};
//Container activity must implement this interface so that the fragment can deliver information
public interface OnSubmitListener {
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable);
}
public void onAttach(MainActivity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnSubmitListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSubmitListener");
}
}
mAddContact = (Button) view.findViewById(R.id.btnAddContactToArray);
mAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...
mCallback.onSubmitClickedContacts(contact, position, updateVariable);
Toast.makeText(getContext(),"I got clicked",Toast.LENGTH_SHORT).show();
}
这是我的MainActivity中的代码。从我所能说的一切看起来都是正确的。但我的日志消息永远不会运行,当我点击“添加联系人”按钮时没有任何反应。
@Override
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable) {
Log.d("TAG", "I got data");
ContactListFragment firstFragment = new ContactListFragment();
//ContactListFragment firstFragment = (ContactListFragment) getSupportFragmentManager()
// .findFragmentById(R.id.fragmentContainer);
Bundle args = new Bundle();
args.putSerializable(CONTACT_OBJECT, contact);
args.putInt(UPDATE_POSITION_INDEX, position);
args.putString(UPDATE_VARIABLE_INDEX, updateVariable);
firstFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, firstFragment);
transaction.addToBackStack(null);
transaction.commit();
}
非常感谢任何帮助。完整代码如下。
activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="@+id/fragmentContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.v7.widget.Toolbar
android:id="@+id/activityToolbar1"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</FrameLayout>
MainActivity:
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements AppStatics, ContactListFragment.OnSubmitListener, ContactFragment.OnSubmitListener{
private Toolbar mToolbar;
private ActionBar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//wiring up the toolbar and action bars
mToolbar = (Toolbar) findViewById(R.id.activityToolbar1);
if (mToolbar != null) {
//pass the activity toolbar
setSupportActionBar(mToolbar);
mActionBar = getSupportActionBar();
mActionBar.setSubtitle("Contact List");
}
if(findViewById(R.id.fragmentContainer) != null) {
//create an instance of NameFragment
ContactListFragment firstFragment = new ContactListFragment();
//in case this gets started with any special instructions from an
//intent, pass the Intent extras as arguments
firstFragment.setArguments(getIntent().getExtras());
//add the fragment to the fragment_container FrameLayout
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer,firstFragment)
.addToBackStack(null)
.commit();
}
}
public void onSubmitClicked (Contacts contact, int position) {
ContactFragment secondFragment = new ContactFragment();
Bundle args = new Bundle();
args.putSerializable(CONTACT_OBJECT, contact);
args.putInt(UPDATE_POSITION_INDEX, position);
secondFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, secondFragment);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable) {
Log.d("TAG", "I got data");
ContactListFragment firstFragment = new ContactListFragment();
//ContactListFragment firstFragment = (ContactListFragment) getSupportFragmentManager()
// .findFragmentById(R.id.fragmentContainer);
Bundle args = new Bundle();
args.putSerializable(CONTACT_OBJECT, contact);
args.putInt(UPDATE_POSITION_INDEX, position);
args.putString(UPDATE_VARIABLE_INDEX, updateVariable);
firstFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, firstFragment);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
ContactFragment:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v7.widget.Toolbar;
/**
* Created by Spheven on 11/25/2015.
*/
public class ContactFragment extends Fragment implements AppStatics {
private EditText mFirst;
private EditText mLast;
private EditText mEmailAddress;
private EditText mPhone;
private Button mAddContact;
private String sFirstName;
private String sLastName;
private String sEmail;
private String sPhone;
private Contacts contact;
ActionBar actionBar;
String updateVariable = "add";
int position;
OnSubmitListener mCallback = new OnSubmitListener() {
@Override
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable) {
}
};
//Container activity must implement this interface so that the fragment can deliver information
public interface OnSubmitListener {
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable);
}
public void onAttach(MainActivity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
mCallback = (OnSubmitListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSubmitListener");
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_contact, container, false);
Bundle args = getArguments();
if (args != null) {
contact = (Contacts) args.getSerializable(CONTACT_OBJECT);
position = args.getInt(UPDATE_POSITION_INDEX, 0);
mFirst.setText(contact.getmFirstName());
mLast.setText(contact.getmLastName());
mEmailAddress.setText(contact.getmEmail());
mPhone.setText(contact.getmPhoneNumber());
mAddContact.setText("Update");
updateVariable = "update";
}
//wiring up text widgets
mFirst = (EditText) view.findViewById(R.id.editFirstName);
mLast = (EditText) view.findViewById(R.id.editLastName);
mEmailAddress = (EditText) view.findViewById(R.id.editEmail);
mPhone = (EditText) view.findViewById(R.id.editPhone);
//wiring up add contact button. includes logic for required fields and sending contact back
//to main activity
mAddContact = (Button) view.findViewById(R.id.btnAddContactToArray);
mAddContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//check that required fields are filled in
if (mFirst.getText().toString().trim().equals("")) {
mFirst.setError("First name is required");
} else if (mLast.getText().toString().trim().equals("")) {
mLast.setError("Last name is required");
} else {
//create new Contacts object and add information to it
sFirstName = mFirst.getText().toString();
sLastName = mLast.getText().toString();
sEmail = mEmailAddress.getText().toString();
sPhone = mPhone.getText().toString();
Contacts contact = new Contacts(sFirstName, sLastName, sEmail, sPhone);
mCallback.onSubmitClickedContacts(contact, position, updateVariable);
Toast.makeText(getContext(),"I got clicked",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
public boolean onCreateOptionsMenu(Menu menu) {
//return super.onCreateOptionsMenu(menu);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.action_add_contact).setVisible(false).setEnabled(false);
menu.findItem(R.id.action_help).setVisible(false).setEnabled(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
getActivity().onBackPressed();
actionBar.setDisplayHomeAsUpEnabled(false);
default:
return super.onOptionsItemSelected(item);
}
}
}
ContactListFragment:
public class ContactListFragment extends Fragment implements AppStatics, ContactFragment.OnSubmitListener {
private TextView mContactsAdded;
private ListView mListView;
ObjectArrayAdapter mAdapter;
ArrayList<Contacts> contactsArrayList = new ArrayList<>();
private Contacts contact;
private String updateVariable;
private int position;
OnSubmitListener mCallback = new OnSubmitListener() {
@Override
public void onSubmitClicked(Contacts contact, int position) {
}
};
//Container activity must implement this interface so that the fragment can deliver information
public interface OnSubmitListener {
public void onSubmitClicked(Contacts contact, int position);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@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 {
mCallback = (OnSubmitListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_contact_list,container,false);
//wiring up the contactsAdded
mContactsAdded = (TextView) view.findViewById(R.id.textContactsAdded);
mContactsAdded.setText("Contacts Added: " + contactsArrayList.size());
//wiring up the adapter
mAdapter = new ObjectArrayAdapter(getContext(), R.layout.contacts_list, contactsArrayList);
//wire up list view
mListView = (ListView) view.findViewById(android.R.id.list);
//display the list
mListView.setAdapter(mAdapter);
//display the "no items to display" message only if list view is empty
mListView.setEmptyView(view.findViewById(android.R.id.empty));
//set on click listener for listview
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Contacts contact = (Contacts) mListView.getAdapter().getItem(position);
/*Intent intent = new Intent(MainActivity.this, ContactActivity.class);
intent.putExtra(CONTACT_OBJECT2, contact);
intent.putExtra(UPDATE_POSITION_INDEX, position);
startActivityForResult(intent, 0);*/
mCallback.onSubmitClicked(contact, position);
}
});
return view;
}
@Override
public void onSubmitClickedContacts(Contacts contact, int position, String updateVariable) {
if (updateVariable.equals("update")) {
contactsArrayList.set(position,contact);
} else {
contactsArrayList.add(contact);
}
mContactsAdded.setText("Contacts Added: " + contactsArrayList.size());
mAdapter.notifyDataSetChanged();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(KEY_INDEX, contactsArrayList);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/*contactsArrayList = (ArrayList<Contacts>)savedInstanceState.getSerializable(KEY_INDEX);
mContactsAdded.setText("Contacts Added: " + contactsArrayList.size());
mAdapter = new ObjectArrayAdapter(getContext(), R.layout.contacts_list, contactsArrayList);
mListView.setAdapter(mAdapter);*/
}
public boolean onCreateOptionsMenu(Menu menu) {
//return super.onCreateOptionsMenu(menu);
menu.clear();
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
/*public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if(android.R.id.home == 16908332) {
menu.findItem(android.R.id.home).setVisible(false).setEnabled(false);
}
}*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_add_contact:
ContactFragment secondFragment = new ContactFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, secondFragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
case R.id.action_help:
Toast.makeText(getContext(), "Help is on the way!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}