我有1帧和2片段用于backstack但我遇到了问题。 如果我将片段2添加到帧并添加到Backstack。我可以点击fragment2上的同一个地方,但效果是在片段1上。我怎么能解决这个问题?非常感谢!
Fragment1.java
public class Fragment1 extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_1,container,false);
Button b = (Button)view.findViewById(R.id.btn1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"FR1",Toast.LENGTH_SHORT).show();
}
});
return view;
}
} BackstackActivity
public class BackstackActivity extends AppCompatActivity {
private Button btnFrag;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_backstack);
btnFrag = (Button) findViewById(R.id.btn_replace_fragment);
btnFrag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addFragment(new Fragment2());
Log.e("Replaced fragment", "2");
}
});
replaceFragmentContent(new Fragment1());
}
protected void replaceFragmentContent(Fragment fragment) {
if (fragment != null) {
FragmentManager fmgr = getSupportFragmentManager();
FragmentTransaction ft = fmgr.beginTransaction();
ft.replace(R.id.container_body, fragment);
ft.commit();
}
}
protected void addFragment(Fragment fragment) {
FragmentManager fmgr = getSupportFragmentManager();
FragmentTransaction ft = fmgr.beginTransaction();
ft.add(R.id.container_body, fragment);
ft.addToBackStack(fragment.getClass().getSimpleName());
ft.commit();
}
}
答案 0 :(得分:0)
在fragment2
布局xml文件中,将根布局设置为clickable="true"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:clickable="true"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="match_parent">