如何在android中动态创建按钮而不扩展活动
我在android中有一个类扩展了Fragment。我需要动态创建一个按钮。我不能使用新按钮(这个)。因为我没有扩展活动。我该怎么做如何在android中动态创建按钮而不扩展活动,android,button,dynamic,android-activity,dynamically-generated,Android,Button,Dynamic,Android Activity,Dynamically Generated,我在android中有一个类扩展了Fragment。我需要动态创建一个按钮。我不能使用新按钮(这个)。因为我没有扩展活动。我该怎么做 public class Tab2Fragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LinearLayout
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);
//尝试使用下面的代码 sol1:
Button myButt=new Button(YourFragmentClass.this);
Button myButt=new Button(getApplicationContext());
sol2:
Button myButt=new Button(YourFragmentClass.this);
Button myButt=new Button(getApplicationContext());
//您也可以像这样获得上下文
private Context mFragmentContext=getActivity().getApplicationContext();
//尝试使用下面的代码 sol1:
Button myButt=new Button(YourFragmentClass.this);
Button myButt=new Button(getApplicationContext());
sol2:
Button myButt=new Button(YourFragmentClass.this);
Button myButt=new Button(getApplicationContext());
//您也可以像这样获得上下文
private Context mFragmentContext=getActivity().getApplicationContext();
有关getView()的更多信息,请参见此处:
快乐编码
有关getView()的更多信息,请参见此处:
快乐编码…传递活动或应用程序上下文而不是“this”。我尝试创建一个新活动并将其放在“this”的空格中,但应用程序崩溃了。我应该在哪里传递活动?对不起,我是个新手。我如何知道应用程序上下文是什么?您的“setContentView”在哪里?它是一个片段,因此我使用此方法LinearLayout theLayout=(LinearLayout)充气器。充气(R.layout.tab2,container,false);我将它添加到我的代码传递活动或应用程序上下文中,而不是“this”。我尝试创建一个新活动并将其放在“this”的空格中,但应用程序崩溃了。我应该在哪里传递活动?对不起,我是个新手。我如何知道应用程序上下文是什么?您的“setContentView”在哪里?它是一个片段,因此我使用此方法LinearLayout theLayout=(LinearLayout)充气器。充气(R.layout.tab2,container,false);我将其添加到我的代码中OK我正在尝试你发布的私有上下文方法,但是我如何将按钮添加到我的视图中,使其实际显示在应用程序中?如果不发布你的代码,你是否希望完成所有作业。好的,我编辑了它并添加了我的代码,addContentView方法在一个活动被扩展的类上工作,但在我的片段类上没有。好的,我正在尝试你发布的私有上下文方法,但是我如何将按钮添加到我的视图中,使它实际显示在应用程序中?如果不发布你的代码,你想做所有的作业。好的,我编辑了它并添加了我的代码,addContentView方法适用于活动已扩展的类,但不适用于我的片段类