如何在android中动态创建按钮而不扩展Activity

时间:2012-07-16 15:50:30

标签: android button dynamic android-activity dynamically-generated

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

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); 

2 个答案:

答案 0 :(得分:3)

//尝试使用以下代码

<强> SOL1:

Button myButt=new Button(YourFragmentClass.this);

<强> SOL2:

Button myButt=new Button(getApplicationContext());

//你也可以获得这样的上下文

 private Context mFragmentContext=getActivity().getApplicationContext(); 

答案 1 :(得分: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

快乐编码......