如何在Fragment中填充视图

44
如果我尝试在片段中膨胀视图,我会得到NULL。例如:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Here I will inflate my view using the layout ID & return.
    return view;
}

每当按钮被点击时,我需要创建一个动态视图,例如:按钮和添加到LinearLayout中。我想在我的片段类中执行此操作,就像这样:

每当点击按钮时,我需要在我的片段类中创建一个动态视图,例如将按钮添加到 LinearLayout 中。请按照以下方式进行:

public void addPlaces() {    
    Button button = new Button(null);
    button.setText("button name");
    // e.g. like adding button to enter code here linear layout
    linearLayout.addView(button); 
}
所以,如果我在onCreateView中inflate LinearLayout并在add类中使用它,我会得到NULL。如何解决?

1
onCreateView 中初始化 LinearLayout。将 LinearLayout 声明为类成员并在 addPlaces 中使用它。 - Raghunandan
你从哪里得到了null?另外,不要使用new Button(null),请传递一个Context而不是null - SimonSays
1个回答

76

将变量声明为实例变量,然后初始化线性布局。

LinearLayout linearLayout;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    return rootView;
}

然后

public void addPlaces() {
    Button button = new Button(getActivity());
    // needs activity context
    // fragment hosted by a activity. use getActivity() to get the context of the hosting activity. 
    button.setText("button name");
    linearlayout.addView(button);
}

示例:根据您的要求修改下面的内容。

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Button" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:id="@+id/linearlayout"
        android:layout_height="fill_parent"
        android:layout_above="@+id/button1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

Myfragment.java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                addPlaces();
            }

        });
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}

我的模拟器快照

在此输入图片描述

编辑:

activity-main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

     <fragment android:name="com.example.fragments.Myfragment"
            android:id="@+id/frag"
            android:layout_above="@+id/button1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

      <Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentBottom="true"
          android:layout_centerHorizontal="true"
          android:text="Button" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends FragmentActivity {
    Button b;
    Myfragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragment = new Myfragment();
        fragmentTransaction.add(R.id.frag, fragment);
        fragmentTransaction.commit();
        b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.addPlaces();
            }

        });
    }
}

Myfragment.java

public class Myfragment extends Fragment {

    LinearLayout linearLayout;
    View rootView;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        linearLayout = (LinearLayout) rootView.findViewById(R.id.linearlayout);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }

    public void addPlaces() {
        Button button = new Button(getActivity()); // needs activity context
        button.setText("button name");
        linearLayout.addView(button);
    }
}

嗨,如果我调用GRPlacesFragment grplaces = new GRPlacesFragment(); getSupportFragmentManager().beginTransaction().add(R.id.myresqplaces, grplaces).commit();grplaces.addPlaces(this); 如果我这样做,我的控制根本没有触发onCreateView方法。 - Naruto
不需要传递“this”,只需使用“getActivity()”即可。 - Raghunandan
肯定的,我正在从FragmentActivity中调用,所以我现在将尝试您的代码。 - Naruto
嗨,我有一个疑问,我们可以使用FrameLayout代替Fragment吗? - Naruto
@LLL 将您的初始化移动到 onActivityCreated,然后它就会工作。 - Raghunandan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接