你好,游客 登录 注册 搜索
背景:
阅读新闻

Button、CheckBox、RadioGroup -

[日期:2013-04-13] 来源:  作者: [字体: ]

Button


监听单击Button

public class MainActivity extends Activity implements OnClickListener {
    private Button bt;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = (Button) findViewById(R.id.bt);
        bt.setOnClickListener(this);
    }

    public void onClick(View v) {
        bt.setText("you have clicked!");
    }
}

 

CheckBox

CheckBox是从CompoundButton中继承的,而CompoundButton是继承TextView。

 

public class MainActivity extends Activity implements
        CompoundButton.OnCheckedChangeListener {
    private CheckBox cb;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cb = (CheckBox) findViewById(R.id.cb);
        cb.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        cb.setText("This checkbox is : " + (isChecked ? "checked" : "unchcked"));
    }

}

 

 

RadioGroup,常见的方法包括有check(),例如roup.check(R.id.radio1)),将R.id.radio1对应的radiobutton选上;clearCheck(),清楚所有的选择,全部都是unchecked;getCheckedRadioButtonId(),获取选上的radiobutton的ID,无则返回-1。

 

public class MainActivity extends Activity implements
        RadioGroup.OnCheckedChangeListener {
    private RadioGroup rg;
    private TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg = (RadioGroup) findViewById(R.id.rg);
        tv = (TextView) findViewById(R.id.tv);
        rg.setOnCheckedChangeListener(this);
    }

    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int radioId = rg.getCheckedRadioButtonId();
        if (radioId < 0)
            tv.setText("No Radio Button is selected");
        else {
            RadioButton rb = (RadioButton) group.findViewById(radioId);
            tv.setText("radio button: " + rb.getText() + " is selected");
        }
    }
}

 

 






收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻