我一直在尝试动态地将textview添加到我的片段中,但它导致应用程序崩溃,下面的代码在非片段活动中工作,我只是无法在片段中使用它。目前我的代码只使用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
答案 0 :(得分:2)
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