我是这个编程世界的新手,所以我想这个问题很简单。所以我在我的片段上有一个图像按钮,我whatI想要的是,当我点击它时,它会对另一个片段执行片段事务;但问题是,当我运行这个应用程序并点击图像按钮时,它只会将另一个片段的内容“叠加”到一个图像按钮上,当然,我想做的就是去另一个片段,我已经处理了很长一段时间了,所以我希望有人能帮我,谢谢。
下面是我的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中得到了这个错误:
无法启动活动ComponentInfo{com.example.administradora.prueba/com.example.administradora.prueba.MainActivity}:java.lang.ClassCastException: com.example.administradora.prueba.MainActivity@20f8fe9b必须实现OnSelectedListener
发布于 2016-08-14 00:28:07
你不应该从另一个片段中替换一个片段。试着通过活动做到这一点。
为要保存的片段定义一些接口
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;
}
}并从活动中交换接口实现中的片段容器。
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的前两部分是您要寻找的内容。
https://stackoverflow.com/questions/38936964
复制相似问题