【问题标题】:Adding a dynamic textview to a fragmment crashes app将动态文本视图添加到片段崩溃应用程序
【发布时间】:2015-03-16 14:03:22
【问题描述】:

我一直在尝试将 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

【问题讨论】:

    标签: java android dynamic fragment


    【解决方案1】:
    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
    

    【讨论】:

    • 感谢您的帮助,对于其他想要使用此代码的人来说,只需将 theView.getContext 修改为 theView.getContext() 即可。非常感谢 Jaswinder。
    • 是的,我是手写的,所以我在家里搞错了,所以我的家庭系统上没有 eclips,但对所有人都表示感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多