【发布时间】:2013-03-20 13:35:50
【问题描述】:
我正在尝试在android中实现片段通信,就像android指南http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity中的那样
但由于 getSupportFragmentManager().findFragmentById() 返回 null,我的应用程序崩溃了。我的实现有什么问题。
代码如下:
该程序只是通过从第一个fragmnet单击按钮将输入文本从一个片段发送到另一个片段textView区域。我有一个activity_main.xml和两个片段布局(两个单独的xml文件,而不是activity_main中的一部分。 xml)
Frag1.java
public class Frag1 extends Fragment {
public Frag1(){
}
buttonClickListener buttonListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
buttonListener = (buttonClickListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnButtonPressListener");
}
}
View myFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.frag1, container, false);
//SetValue Button
Button setValueButton = (Button) myFragmentView.findViewById(R.id.setValueButton);
setValueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
buttonListener.onButtonPressed("Message received");
}
});
return myFragmentView;
}
}
Frag2.java
public class Frag2 extends Fragment {
View myFragmentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.frag2, container, false);
return myFragmentView;
}
void setMessage(String msg){
TextView txt=(TextView)myFragmentView.findViewById(R.id.textView1);
txt.setText(msg);
}
}
buttonClickListener.java
public interface buttonClickListener {
public void onButtonPressed(String msg);
}
MainActivity.java
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, buttonClickListener {
SectionsPagerAdapter mSectionsPagerAdapter;
@Override
public void onButtonPressed(String msg) {
// TODO Auto-generated method stub
Frag2 fragmentObj=(Frag2) getSupportFragmentManager().findFragmentById(R.layout.frag2);
fragmentObj.setMessage(msg);
}
请告诉我哪里出错了?
编辑: 我正在使用由 Android Plug-in eclipse IDE 生成的模板创建片段。 所以片段是使用 android.support.v4.app.Fragment
创建的@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position)
{
case 0:
return new Frag1();
case 1:
return new Frag2();
}
return fragment;
}
代码库保留在这里以供参考 https://skydrive.live.com/redir?resid=D37E0F56FEC9B499!259
【问题讨论】:
-
您使用的是 ActionBarSherlock、支持库还是什么?
-
findFragmentById(R.layout.frag2)。你确定R.layout.flag2,可能是R.id.frag2
-
@gipi 我已经使用了支持库,并且在我的编辑中也进行了更新。
-
@GabrieleMariotti :我没有将 id 添加到片段元素中,因为它们是布局的一部分并且不存在于
元素中。