0

我在 android 中有一个扩展 Fragment 的类。我需要动态创建一个按钮。我不能使用新按钮(这个)。因为我没有扩展活动。我该怎么做呢?

public class Tab2Fragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {


    LinearLayout theLayout =  (LinearLayout) inflater.inflate(R.layout.tab2, container, false);

    Context mFragmentContext=getActivity().getApplicationContext(); 
    Button btn=new Button(mFragmentContext);
    btn.setText("Hello Button");
    RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(150,30);
    paramsd.height = 600;
    paramsd.width = 60;
    btn.setLayoutParams(paramsd);
    addContentView(btn,paramsd); 
4

2 回答 2

3

//尝试使用下面的代码

溶胶1:

Button myButt=new Button(YourFragmentClass.this);

溶胶2:

Button myButt=new Button(getApplicationContext());

//你也可以像这样获取上下文

 private Context mFragmentContext=getActivity().getApplicationContext(); 
于 2012-07-16T16:08:02.960 回答
0
/* getActivity() will give you the Activity this fragment belongs
to, you can use this as 'Context' */

Button button = new Button(getActivity())

/* getView() will give you the root layout for this fragment 
(Relative, Linear or whatever you used in xml) and you must cast it
to a ViewGroup to access the getView() method*/

RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(150,30);
paramsd.height = 600;
paramsd.width = 60;

ViewGroup viewGroup = (ViewGroup) getView();
viewGroup.addView(button, paramsd);

有关 getView() 的更多信息,请参见此处:Android add button to Fragment without id

快乐的编码...

于 2014-03-28T13:49:53.683 回答