从另一个类调用动态按钮

时间:2014-01-24 13:23:29

标签: java android

我是java / Android的新手,我想传递我定义了我的按钮属性的方法。并且该方法是在另一个不能实现Activity的类中编写的。

ex

class ViewProvider extends xyz
{
 public Button getButton(){
       Button one=new Button();
       one.setText("abc");
       one.setTypeface(Typeface.DEFAULT_BOLD);
       //and other properties like color,Gravity ect 
       return one
    }
}

Class calcu extends Activity{
   protected void onCreate(Bundle savedInstanceState) 
      {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.app_list);
        ViewProvider v=new ViewProvider();
       RelativeLayout relativelayout = new RelativeLayout(this);
       relativelayout.addView(v.getButton);
       setContentView(relativelayout);

       }

但我收到了错误

2 个答案:

答案 0 :(得分:2)

只需创建一个Activity数据类型并通过构造函数初始化它,如下所示

class ViewProvider extends xyz
   Activity activity;
{

     public ViewProvider(Activity activity, JSONObject json) {
                      this.activity = activity;
                 }

    public Button getButton(activity){
    Button one=new Button();
    one.setText("abc");
    return one
}

然后在onCreate(Bundle savedInstanceState)上调用如下方法

ViewProvider v=new ViewProvider(this);
      RelativeLayout relativelayout = new RelativeLayout(this);
      relativelayout.addView(v.getButton);
      setContentView(relativelayout);

答案 1 :(得分:1)

如果你看看按钮@的构造函数,你就有错误的参数。

http://developer.android.com/reference/android/widget/Button.html

Button(Context context)
Button(Context context, AttributeSet attrs)
Button(Context context, AttributeSet attrs, int defStyle)

所有这三个都将上下文作为一个参数。

我建议你阅读文档

http://developer.android.com/guide/topics/ui/declaring-layout.html

你也有setContentView两次,这是没有必要的。

在活动本身中初始化按钮

  Class calcu extends Activity{
   @Override
   protected void onCreate(Bundle savedInstanceState) 
   {
      super.onCreate(savedInstanceState);
       RelativeLayout relativelayout = new RelativeLayout(this);
       Button one=new Button(this);
       one.setText("abc");
       relativelayout.addView(one);
       setContentView(relativelayout);
   }
   }