如何在另一个类中设置按钮属性和操作,并在android的Activity类中使用它们

时间:2013-10-08 12:41:06

标签: java android android-layout

请帮我按下Class

下方的Button Action
   public class DoneButtonMain extends MainActivity implements OnClickListener{

        private Activity activity;
        private Context context;


        public DoneButtonMain(Activity activity) {
            this.activity=activity;
            // TODO Auto-generated constructor stub
        }


        public View prepareControl(){

            Button btn=new Button(activity);
            btn.setText("Done");
            btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            btn.setBackgroundColor(Color.parseColor("#05a5a6"));
            btn.setTypeface(Typeface.DEFAULT_BOLD);
            btn.setPadding(7,7, 7, 7);

            btn.setTextColor(Color.parseColor("#ffffff"));

        return btn;


        }

    public LayoutParams prepareLayoutParam() {
        RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        param.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,RelativeLayout.TRUE);
        param.addRule(RelativeLayout.CENTER_VERTICAL,RelativeLayout.TRUE);
        param.rightMargin=20;
        param.bottomMargin=20;
        param.topMargin=20;
        return param;


    }
}

MainActivity 如下所示

public class MainActivity extends Activity {


        @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    LinearLayout parentlinLayout = new LinearLayout(this);
        parentlinLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 


    RelativeLayout raltivelayout1=new RelativeLayout(this);
        raltivelayout1.setBackgroundColor(Color.parseColor("#1B4F91"));

      //Button Added to the relativeLayaout
        DoneButtonMain object=new DoneButtonMain(this);

        raltivelayout1.addView(object.prepareControl(),object.prepareLayoutParam());
        //Relative layout is added to the Linear View
        parentlinLayout.addView(raltivelayout1);
}

我试过button.setOnClickListener但我得到了一个空指针异常

1 个答案:

答案 0 :(得分:3)

谢谢大家,我得到了谅解。因为我已经在DoneButton类中实现了OnClickListener,所以通过activity对象实现了prepareControl。

private void handleBtnClick() {
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

//required code
});
    }