簡體   English   中英

如何在不擴展Activity的情況下在android中動態創建按鈕

[英]How to create a button dynamically in android without extending Activity

我在android中有一個可擴展Fragment的類。 而且我需要動態創建一個按鈕。 我不能使用新的Button(this)。 因為我沒有擴展活動。 我該怎么做呢?

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

//嘗試使用以下代碼

溶膠1:

Button myButt=new Button(YourFragmentClass.this);

sol2:

Button myButt=new Button(getApplicationContext());

//您也可以獲得這樣的上下文

 private Context mFragmentContext=getActivity().getApplicationContext(); 
/* 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向不帶ID的Fragment添加按鈕

快樂編碼...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM