将动态文本视图添加到碎片会导致应用崩溃



我一直在尝试将文本视图动态添加到我的片段中,但它导致应用程序崩溃,下面的代码在非片段活动中工作,我只是无法让它在片段中工作。 目前,我的代码仅在 textview 上使用,但它最终会从数据库中返回许多代码,因此我需要动态创建它。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View theView = inflater.inflate(R.layout.fragment_list_batches, container, false);
    context=getActivity();
    //Dynamically create Elements
    LinearLayout.LayoutParams SVView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    LinearLayout SV = (LinearLayout)getActivity().findViewById(R.id.listBatchesRelative);
    TextView batchName = new TextView(context);
    int i = 1;
    batchName.setId(Integer.valueOf(i));
    batchName.setText("Dynamic Input view");
    batchName.setLayoutParams(SVView);
    SV.addView(batchName);
return theView
View theView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
 theView = inflater.inflate(R.layout.fragment_list_batches, container,false);
LinearLayout.LayoutParams SVView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout SV = (LinearLayout)theView .findViewById(R.id.listBatchesRelative);
TextView batchName = new TextView(theView.getContext);
int i = 1;
batchName.setId(Integer.valueOf(i));
batchName.setText("Dynamic Input view");
batchName.setLayoutParams(SVView);
SV.addView(batchName);
return theView

最新更新