【发布时间】:2018-06-19 15:36:51
【问题描述】:
我正在尝试从另一个 Fragment 类中按钮的 onClick 方法中将片段添加到现有布局中。
在我的 MainActivity 中,我向布局中添加了两个片段..
public class MainActivity extends AppCompatActivity {
private Collapsebutton_Fragment cbut_frag;
private ColourView_Fragment cvw_frag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbut_frag = new Collapsebutton_Fragment();
cvw_frag = new ColourView_Fragment();
//ColourView Fragment ready
//CollapseButton Fragment ready
getSupportFragmentManager().beginTransaction()
.add(R.id.container_mainactivity, cbut_frag)
.add(R.id.container_mainactivity, cvw_frag)
.commit();
}
}
其中一个添加的片段包含一个按钮。单击该按钮时 - 访问按钮的 onClick 方法 - 我想添加另一个片段..
我的代码如下:
public class ColourView_Fragment extends Fragment {
FragmentManager fragmentManager;
ThreeButton_Fragment tbt_fragment;
public ColourView_Fragment(){}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.colourview_fragment, container, false);
FrameLayout frameLayout = (FrameLayout)rootView.findViewById(R.id.ColourView);
frameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.container_mainactivity, tbt_fragment)
.commit();
}
});
return rootView;
}
我收到以下错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.Class java.lang.Object.getClass()”
一行有错误
.add(R.id.container_mainactivity, tbt_fragment)
我该如何纠正?
【问题讨论】:
标签: android