簡體   English   中英

將選定的單選按鈕放入OnClick中以獲取按鈕

[英]Getting the selected radio button inside OnClick for a button

我正在構建一個簡單的應用程序,該應用程序允許用戶輸入他的名字並選擇“帶有名字”單選按鈕,並顯示一個烤面包,Hello Name

來賓向其他廣播電台顯示您好,因此如何在OnClick中獲取選定的廣播電台,我需要從FindViewByID中獲取它們嗎?

這是我的代碼

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(this);

}

public void onClick(View v) {
    if (v.getId() == R.id.button1) {
        //getting the selected radio if its radio 0
        Toast.makeText(this, "Hello Guest", Toast.LENGTH_LONG).show();
    }

    //getting the selected radio if its radio 1
    EditText txt = (EditText) findViewById(R.id.editText1);

    Toast.makeText(this, "Hello " + txt.toString(), Toast.LENGTH_LONG).show();
}

嘗試以下方法:

button.setOnClickListener(new View.OnClickListener(){
    public void onClick(View v){
        //YOUR CODE HERE
    }
});

將其放在onCreate()中,看看如何實現。 您是否還嘗試查看傳遞給onClick的View v Id是否實際上是正確的視圖? 要查看此信息,請使用日志檢查ID。

最好您直接在按鈕單擊偵聽器上檢查單選按鈕狀態:

 @Override
public void onClick(View v) 

{
if(v == button)
{

if(rb1.isChecked() == true)
Toast.makeText(this, "Hello"+rb1.getText(), Toast.LENGTH_LONG).show();

if(rb2.isChecked() == true)
Toast.makeText(this, "Hello"+rb2.getText(), Toast.LENGTH_LONG).show();
}
}

哪里

rb1=(RadioButton)findViewById(R.id.optname);
rb2=(RadioButton)findViewById(R.id.optguest);

更多

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM