Android添加按钮到Fragment没有id

时间:2013-09-20 09:45:16

标签: android android-fragments

我想在片段的左下角显示一个按钮,但我不知道片段主要布局的ID,因为我在一个没有布局的抽象类中。

@EFragment(R.layout.exercise_test)
public class Exercise1 extends Exercice

public abstract class Exercice extends Fragment{

   public void showValidateButton()
   {
       Button validateButton = new Button(this.getActivity().getBaseContext());
       validateButton.setText("OK");
       // Here I want to add the button to Exercise1 
   }
}

有没有办法实现这个目标?

谢谢

亨利。

1 个答案:

答案 0 :(得分:1)

您可以使用Fragment的getView()方法获取包含片段所有布局的根视图。只要这是ViewGroup,您就可以使用addView()方法添加Button。

但是,如果正确放置,您可以了解所使用的布局,例如: RelativeLayout,LinearLayout等。

更硬核的解决方案是创建自己的RelativeLayout,添加Fragment的getView()和你自己的Button的结果,并将RelativeLayout设置为片段的新根视图。