android中RadioGroup、RadioButton、Spinner、EditText用法詳解(含樣本截圖和原始碼)

來源:互聯網
上載者:User

android中RadioGroup、RadioButton、Spinner、EditText用法詳解(含樣本和原始碼)

 

今天在項目中用到了android中常用的RadioGroup、RadioButton、Spinner、EditText等控制項,在此介紹一下它們的用法,希望對需要的朋友有協助。

一、RadioGroup和RadioButton的使用

RadioButton就是我們常見的選項按鈕,一個RadioGroup可以包含多個選項按鈕,但是每次只能選擇其中的一個值。

我們先看一下布局檔案:

 

           
再來看一下RadioGroup的監聽器介面:RadioGroup.OnCheckedChangeListener

 

 

 public interface OnCheckedChangeListener {        /**         * 

Called when the checked radio button has changed. When the * selection is cleared, checkedId is -1.

* * @param group the group in which the checked radio button has changed * @param checkedId the unique identifier of the newly checked radio button */ public void onCheckedChanged(RadioGroup group, int checkedId); } 我們需要實現RadioGroup.OnCheckedChangeListener介面,重寫onCheckedChanged(RadioGroup group, int checkedId)函數,參數group指定添加監聽器的RadioGroup,參數checkedId指定選中的RadioButton的ID。

 

二、Spinner的使用

Spinner是下拉式清單選擇框,可以綁定資料來源,資料來源可以在程式中定義,也可以在values/strings中定義字串數組,還可以在資料庫中查詢擷取。

布局很簡單,詳見後面的例子。

綁定資料來源:

 

String[] intervalTime = getResources().getStringArray(R.array.intervalTime);ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, intervalTime);bstIntervalSpinner.setAdapter(adapter);
設定監聽器介面:AdapterView.OnItemSelectedListener

 

 

public interface OnItemSelectedListener {        /**         * 

Callback method to be invoked when an item in this view has been * selected. This callback is invoked only when the newly selected * position is different from the previously selected position or if * there was no selected item.

* * Impelmenters can call getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param parent The AdapterView where the selection happened * @param view The view within the AdapterView that was clicked * @param position The position of the view in the adapter * @param id The row id of the item that is selected */ void onItemSelected(AdapterViewparent, View view, int position, long id); /** * Callback method to be invoked when the selection disappears from this * view. The selection can disappear for instance when touch is activated * or when the adapter becomes empty. * * @param parent The AdapterView that now contains no selected item. */ void onNothingSelected(AdapterViewparent); } 我們需要實現AdapterView.OnItemSelectedListener介面,重寫onItemSelected(AdapterViewparent, View view, int position, long id)方法。

 

三、EditText的使用

EditText很常見,用來輸入文本,給它添加監聽器可以即時監測已經輸入的常值內容,包括查看是否有錯誤、輸入是否符合規範、長度是否超出了範圍。

添加監聽器:

 

powerEditText.addTextChangedListener(editTextListener);
監聽器實現TextWatcher介面:

 

 

public interface TextWatcher extends NoCopySpan {    /**     * This method is called to notify you that, within s,     * the count characters beginning at start     * are about to be replaced by new text with length after.     * It is an error to attempt to make changes to s from     * this callback.     */    public void beforeTextChanged(CharSequence s, int start,                                  int count, int after);    /**     * This method is called to notify you that, within s,     * the count characters beginning at start     * have just replaced old text that had length before.     * It is an error to attempt to make changes to s from     * this callback.     */    public void onTextChanged(CharSequence s, int start, int before, int count);    /**     * This method is called to notify you that, somewhere within     * s, the text has been changed.     * It is legitimate to make further changes to s from     * this callback, but be careful not to get yourself into an infinite     * loop, because any changes you make will cause this method to be     * called again recursively.     * (You are not told where the change took place because other     * afterTextChanged() methods may already have made other changes     * and invalidated the offsets.  But if you need to know here,     * you can use {@link Spannable#setSpan} in {@link #onTextChanged}     * to mark your place and then look up from here where the span     * ended up.     */    public void afterTextChanged(Editable s);}
我們可以根據需要重寫beforeTextChanged(CharSequence s, int start, int count, int after)、onTextChanged(CharSequence s, int start, int before, int count)、afterTextChanged(Editable s)這三個方法。

 

四、樣本和原始碼

先上:

在中,有3個RadioGroup、2個Spinner和1個EditText,由於程式中設定了監聽器,所以上面選項設定的值都會在分割線下面即時顯示出結果。

原始碼:

布局檔案:

                                                                                                                                                                                                                                                                                                                        
Java類檔案:

 

 

package readAndWriteOBU;import android.app.Activity;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.EditText;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.Spinner;import android.widget.TextView;import com.hustxks.etcapp.R;public class InitActivity extends Activity{//忽略快速響應幀單選框private RadioGroup quickResponseRadioGroup;private RadioButton yesRadioButton;private RadioButton noRadioButton;//BST間隔下拉式清單private Spinner bstIntervalSpinner;    //交易稍候再試下拉式清單private Spinner transIntervalSpinner;//功率級數編輯框private EditText powerEditText;//通道號單選框private RadioGroup channelNumRadioGroup;private RadioButton channelRadioButton1;private RadioButton channelRadioButton2;//CRC校正單選框private RadioGroup crcCkeckRadioGroup;private RadioButton crcRadioButton1;private RadioButton crcRadioButton2;//是否忽略快速響應幀標誌:00:忽略快速響應 01:完全透傳public static String ignoreQuickResFlag = 0;//BST間隔,單位ms,範圍1~10mspublic static String bstInterval = 10;//交易稍候再試,單位ms,範圍1~10mspublic static String transRetryInterval = 10;//功率級數,範圍0~31public static String power = 5;//通道號,取值0,1public static String channelID = 0;//CRC校正標誌位,取值0,1public static String crcCheckFlag = 0;private String[] intervalTime;//顯示設定結果文字框TextView resultTextView1;TextView resultTextView2;TextView resultTextView3;TextView resultTextView4;TextView resultTextView5;TextView resultTextView6;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.init_activity);initView();RadioGroupListener quickRadioGroupListener = new RadioGroupListener(quickResponseRadioGroup);RadioGroupListener channelRadioGroupListener = new RadioGroupListener(channelNumRadioGroup);RadioGroupListener crcRadioGroupListener = new RadioGroupListener(crcCkeckRadioGroup);EditTextListener editTextListener = new EditTextListener();quickResponseRadioGroup.setOnCheckedChangeListener(quickRadioGroupListener);channelNumRadioGroup.setOnCheckedChangeListener(channelRadioGroupListener);crcCkeckRadioGroup.setOnCheckedChangeListener(crcRadioGroupListener);powerEditText.addTextChangedListener(editTextListener);intervalTime = getResources().getStringArray(R.array.intervalTime);ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, intervalTime);bstIntervalSpinner.setAdapter(adapter);transIntervalSpinner.setAdapter(adapter);SpinnerListener bstSpinnerListener = new SpinnerListener(bstIntervalSpinner);bstIntervalSpinner.setOnItemSelectedListener(bstSpinnerListener);SpinnerListener retrySpinnerListener = new SpinnerListener(transIntervalSpinner);transIntervalSpinner.setOnItemSelectedListener(retrySpinnerListener);}private void initView() {quickResponseRadioGroup = (RadioGroup)findViewById(R.id.quickResponseRG);yesRadioButton = (RadioButton)findViewById(R.id.yesRadioButton);noRadioButton = (RadioButton)findViewById(R.id.noRadioButton);bstIntervalSpinner = (Spinner)findViewById(R.id.BSTintervalSpinner);transIntervalSpinner = (Spinner)findViewById(R.id.transRetrySpinner);powerEditText = (EditText)findViewById(R.id.powerEditText);channelNumRadioGroup = (RadioGroup)findViewById(R.id.channelNumRG);channelRadioButton1 = (RadioButton)findViewById(R.id.channelRadioButton1);channelRadioButton2 = (RadioButton)findViewById(R.id.channelRadioButton2);crcCkeckRadioGroup = (RadioGroup)findViewById(R.id.crcCheckRG);crcRadioButton1 = (RadioButton)findViewById(R.id.crcRadioButton1);crcRadioButton2 = (RadioButton)findViewById(R.id.crcRadioButton2);resultTextView1 = (TextView)findViewById(R.id.result1);resultTextView2 = (TextView)findViewById(R.id.result2);resultTextView3 = (TextView)findViewById(R.id.result3);resultTextView4 = (TextView)findViewById(R.id.result4);resultTextView5 = (TextView)findViewById(R.id.result5);resultTextView6 = (TextView)findViewById(R.id.result6);}//監聽RadioGroup的類class RadioGroupListener implements RadioGroup.OnCheckedChangeListener {private RadioGroup myRadioGroup;public RadioGroupListener(RadioGroup radioGroup) {// TODO Auto-generated constructor stubthis.myRadioGroup = radioGroup;}@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubswitch (myRadioGroup.getId()) {case R.id.quickResponseRG:if (checkedId == R.id.yesRadioButton) {ignoreQuickResFlag = 00;}else if (checkedId == R.id.noRadioButton) {ignoreQuickResFlag = 01;}resultTextView1.setText(ignoreQuickResFlag);break;case R.id.channelNumRG:if (checkedId == R.id.channelRadioButton1) {channelID = channelRadioButton1.getText().toString().trim();}else if (checkedId == R.id.channelRadioButton2) {channelID = channelRadioButton2.getText().toString().trim();}resultTextView5.setText(channelID);;break;case R.id.crcCheckRG:if (checkedId == R.id.crcRadioButton1) {crcCheckFlag = crcRadioButton1.getText().toString().trim();}else if (checkedId == R.id.crcRadioButton2) {crcCheckFlag = crcRadioButton2.getText().toString().trim();}resultTextView6.setText(crcCheckFlag);break;default:break;}}}//監聽EditText的類class EditTextListener implements TextWatcher {@Overridepublic void beforeTextChanged(CharSequence s, int start,                int count, int after) {}@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void afterTextChanged(Editable s) {power = powerEditText.getText().toString().trim();resultTextView4.setText(power);}}//監聽Spinner的類class SpinnerListener implements AdapterView.OnItemSelectedListener {private Spinner mySpinner;public SpinnerListener(Spinner spinner) {// TODO Auto-generated constructor stubthis.mySpinner = spinner;}@Overridepublic void onItemSelected(AdapterView parent, View view,int position, long id) {if (mySpinner.getId() == R.id.BSTintervalSpinner) {bstInterval = intervalTime[position];resultTextView2.setText(bstInterval);}else if (mySpinner.getId() == R.id.transRetrySpinner) {transRetryInterval = intervalTime[position];resultTextView3.setText(transRetryInterval);}}@Overridepublic void onNothingSelected(AdapterView parent) {}}}
 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.