我尝试了很多东西,例如 2 个参考:http: //developer.android.com/training/basics/fragments/communicating.html & http://developer.android.com/guide/components/fragments.html# CommunicatingWithActivity以及 StackOverflow 上其他人的一些帮助,我只是无法让我的 ListFragment (FragmentA) 仅将一个简单的字符串发送到另一个 ListFragment (FragmentB)。当我单击 FragmentA 中的列表进入 FragmentB 时,我的应用程序不断崩溃,告诉我有一个 NullPointerException。我已经坚持了 2 天了,我只是想把头撞在墙上。如果有人知道出了什么问题,请发布代码来解决我的问题。
主要活动:
import com.example.fragmentcommunication.FragmentB.OnDataPass;
public class MainActivity extends Activity implements OnDataPass{
...
@Override
public void onCreate(Bundle savedInstanceState) {
...
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String librarySelected = libraryList[position];
Fragment newFragment = null;
if (librarySelected.equals("Item1")){
newFragment = new FragmentA();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.tab2, newFragment, "FragA");
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
});
}
public void onDataPass(String data) {
// TODO Auto-generated method stub
FragmentB transaction1 = ((FragmentB) getFragmentManager().findFragmentByTag("FragB"));
transaction1.use(data);
}
}
片段A:
public class FragmentA extends ListFragment{
...
OnDataPass dataPasser;
public interface OnDataPass{
public void onDataPass(String data);
}
@Override
public void onAttach(Activity a) {
super.onAttach(a);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
dataPasser = (OnDataPass) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String libraryList;
//Get the position the user clicked.
Fragment newFragment = null;
libraryList = l.getItemAtPosition(position).toString();
dataPasser.onDataPass(libraryList);
if(libraryList.equals("Ranged")){
newFragment = new FragmentB();
}
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.tab2, newFragment, "FragB");
transaction.addToBackStack(null);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
}
片段B:
public class FragmentB extends ListFragment{
...
String getListInfo;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
//Testing to see if the String was passed from Fragment A.
System.out.println(getListInfo);
...
public void use(String data) {
// TODO Auto-generated method stub
this.getListInfo = data;
}
}