我是这个编程世界的新人,所以我想这个问题很简单。所以我的片段上有一个图像按钮,我想要的是当我点击它时,它会对另一个片段进行片段事务处理;但问题是,当我运行应用程序并单击图像按钮时,它只会"叠加"将另一个片段的内容放入图像按钮所在的那个,当然我要做的只是去另一个片段,我已经处理了一段时间,所以我希望有人帮助我,谢谢。
这是片段
的java代码public class inicio extends Fragment {
public inicio() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_inicio,container,false);
ImageButton luces = (ImageButton)view.findViewById(R.id.imageButton);
luces.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
interior interior= new interior();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.inicioo, interior).commit();
}
});
}
}
新增代码......
public class transaction extends MainActivity
implements com.example.administradora.prueba.inicio.OnSelectedListener{
public void onButtonSelected() {
interior interior= new interior();
getSupportFragmentManager().beginTransaction().replace(R.id.inicioo, interior).commit();
}
}
但是我在logcat中得到了这个错误:
java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.administradora.prueba / com.example.administradora.prueba.MainActivity}:java.lang.ClassCastException:com.example.administradora.prueba.MainActivity @ 20f8fe9b必须实现OnSelectedListener
答案 0 :(得分:-1)
您不应该从另一个片段替换片段。尝试通过活动来做到这一点。
为Fragment定义一些接口
public class MyFragment extends Fragment {
OnSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnSelectedListener {
public void onButtonSelected();
}
@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 = (OnSelectedListener ) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnSelectedListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_inicio,container,false);
ImageButton luces = (ImageButton)view.findViewById(R.id.imageButton);
luces.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Send the event to the host activity
if (mCallback != null) mCallback.onButtonSelected();
}
});
return view;
}
}
并从Activity中交换接口实现中的Fragment容器。
public class MainActivity extends Activity
implements MyFragment.OnSelectedListener{
...
public void onButtonSelected() {
interior interior= new interior();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.inicioo, interior)
.commit();
}
}
Communicating with Other Fragments的前两部分正是您要找的。