【问题标题】:Can't inflate layout properly for a fragment in Android application无法为 Android 应用程序中的片段正确膨胀布局
【发布时间】:2014-07-03 15:12:10
【问题描述】:

首先这是片段的代码:

public class MyFragment extends Fragment {
    private View FragmentView;

    public static Fragment newInstance() {
        MyFragment NewFragment = new MyFragment();
        return NewFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        FragmentView = inflater.inflate(
            R.layout.tasks, 
            new LinearLayout(MainActivity.MainContext)
        );
        FragmentView.setLayoutParams(
            new LayoutParams(
                LayoutParams.MATCH_PARENT, 
                LayoutParams.MATCH_PARENT
            )
        );
        addText();

        return FragmentView;
    }

    private void addText() {
        TasksView.setBackgroundResource(R.drawable.bg_image);
        TextView MyTitle = new TextView(MainActivity.MainContext);
        MyTitle.setLayoutParams(
            new LayoutParams(
                LayoutParams.MATCH_PARENT, 
                LayoutParams.WRAP_CONTENT
            )
        );

        MyTitle.setText(R.string.mytitle);
        ((LinearLayout) FragmentView).addView(MyTitle );
    }
}

MainActivity.MainContextpublic static 存储在主活动的类中,并在getApplicationContext() 创建活动时检索。

现在,问题出在这里:

 FragmentView = inflater.inflate(
     R.layout.tasks, 
     new LinearLayout(MainActivity.MainContext)
 );

因此,MyTitle 文本视图不会显示在片段内。如果我这样做:

FragmentView = inflater.inflate(R.layout.tasks, null);

它已显示,但我收到警告:

Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)

我想正确地执行此操作,并且不会收到任何警告,但我找不到方法。我也试过:

FragmentView = inflater.inflate(R.layout.tasks, container);

但应用程序崩溃了。

【问题讨论】:

    标签: android textview fragment layout-inflater


    【解决方案1】:

    您应该将container 作为父级传递。

    FragmentView = inflater.inflate(
                R.layout.tasks, 
                container,
                false
            );
    

    您还应该指定false,因此LayoutInflater 不会将膨胀视图附加到父视图。膨胀的视图通过FragmentManager 附加到父视图。

    【讨论】:

    • 有关为什么 null 父级不好的更多信息,请参阅:doubleencore.com/2013/05/layout-inflation-as-intended
    • 谢谢,现在可以使用了。我尝试以相同的方式添加一个新的文本视图(在第一个之后),但我只看到第一个。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多