以编程方式设置按钮和TextView的Id,并根据id执行操作

时间:2015-09-04 21:51:56

标签: java android

我尝试设置按钮和textview的ID,然后尝试在按钮下设置textlay_below of textview。但无法使用我的代码并显示错误:

Button btnMakeObjectRequest=new Button(this);
        btnMakeObjectRequest.setText("Get JSON");
        btnMakeObjectRequest.setId(1);
     TextView   txtResponse = new TextView(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams ( RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT );
        lp.addRule(RelativeLayout.BELOW,1);
        txtResponse.setLayoutParams(lp);

        rl.addView(btnMakeObjectRequest);
        rl.addView(txtResponse);

        setContentView(rl);

1 个答案:

答案 0 :(得分:2)

您应该使用View.generateViewId()方法为视图分配唯一的ID。请注意,这适用于API 17 +

btnMakeObjectRequest.setId(View.generateViewId());

然后当你需要id时只需调用

btnMakeObjectRequest.getId();