首页 > 代码库 > 5.User Interface/Input Controls

5.User Interface/Input Controls

1. Input Controls

  

2. Buttons

  A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

  

  With text, using Button class

  With an icon, using ImageButton class

<ImageButton    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:src="@drawable/button_icon"    ... />

  With text and an icon, using the Button class with the android:drawableLeft attribute

<Button    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/button_text"    android:drawableLeft="@drawable/button_icon"    ... />

  2.1 Responding to Click

<?xml version="1.0" encoding="utf-8"?><Button xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/button_send"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/button_send"    android:onClick="sendMessage" />
/Called when the user touches the button/public void sendMessage(View view) {    // Do something in response to button click}

    Specificlly, the method above must:

    <1> Be public

    <2> Return void

    <3> Define a View as its only parameter(this will be the View that was clicked)

  2.2 Using an OnClickListener 

Button button = (Button) findViewById(R.id.button_send);button.setOnClickListener(new View.OnClickListener() {    public void onClick(View v) {        // Do something in response to button click    }});

  2.3 Styling Your Button

    <1> Borderless button  

<Button    android:id="@+id/button_send"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/button_send"    android:onClick="sendMessage"    style="?android:attr/borderlessButtonStyle" />

    <2> Custom background

      <i> Create three bitmaps for the button background that represent the default, pressed, and focused button states.

        To ensure that your images fit buttons of various sizes, create the bitmaps as Nine-patch bitmaps

      <ii> Place the bitmaps into the res/drawable diectory of your project.    

      <iii> Create a new XML file in the res/drawable directory(name it something like button_custom.xml).

          Insert the following XML

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/button_pressed"          android:state_pressed="true" />    <item android:drawable="@drawable/button_focused"          android:state_focused="true" />    <item android:drawable="@drawable/button_default" /></selector>

      <iiii> Then simply apply the drawable XML file as the button background:

<Button    android:id="@+id/button_send"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="@string/button_send"    android:onClick="sendMessage"    android:background="@drawable/button_custom"  />

 

 

3. Text Filed

  A text field allows the user to type text into your app. It can be either single line or multi-line. Touching a text field places the cursor

    and automatically displays the keyboard. In addition to typing, text fields allow for a variety of other activities, such as text selection

    (cut, copy, paste) and data look-up via auto-completion.

    

  3.1 Specifying the Keyborad Type

    You can specify the type of keyboard you want for your EditText object with the android:inputType attribute

    "text"          Normal text keyboard.

    "textEmailAddress"  Normal text keyboard with the @ character

    "textUri"        Normal text keyboard with the / character.

    "number"         Basic number keypad.

    "phone"         Phone-style keypad.

      defalut text input type

        

      textEmailAddress input Type

        

      phone input type

        

    android:inputType attribute also allows you to specify certain keyboard behaviors,

      "textCapSentences"      Normal text keyboard that capitalizes the first letter for each new sentence.

      "textCapWords"           Normal text keyboard that capitalizes every word. Good for titles or person names.

      "textAutoCorrect"         Normal text keyboard that corrects commonly misspelled words.

      "textPassword"             Normal text keyboard, but the characters entered turn into dots.

    For example, here‘s how you can collect a postal address, capitalize each word, and disable text suggestions:

<EditText    android:id="@+id/postal_address"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:hint="@string/postal_address_hint"    android:inputType="textPostalAddress|                       textCapWords|                       textNoSuggestions" />

  3.2 Specifying Keyboard Actions

    Android allows you to specify an action to be made when users have completed their input. The action specifies the button that

      appears in place of the carriage return key and the action to be made, such as "Search" or "Send."

    You can specify the action by setting the attribute. For example, here‘s how you can specify the Send action:

EditText    android:id="@+id/search"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:hint="@string/search_hint"    android:inputType="text"    android:imeOptions="actionSend" />

    

 

//here‘s how you can listen for when the user clicks the Send button on the keyboard:EditText editText = (EditText) findViewById(R.id.search);editText.setOnEditorActionListener(new OnEditorActionListener() {    @Override    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {        boolean handled = false;        if (actionId == EditorInfo.IME_ACTION_SEND) { //An EditorInfo             sendMessage();            handled = true;        }        return handled;    }});

  3.3 Providing Auto-complete Suggestions

    The following procedure describes how to set up an AutoCompleteTetxView that provides suggestions from an array, using

       ArrayAdapter:

    <1> Add AutoCompleteTextView to your layout. 

<?xml version="1.0" encoding="utf-8"?><AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"     android:id="@+id/autocomplete_country"    android:layout_width="fill_parent"    android:layout_height="wrap_content" />

    <2> Define the array that contains all text suggestions. For example, here‘s an array of country names that‘s defined in an XML

        resource file(res/values/strings.xml)

<?xml version="1.0" encoding="utf-8"?><resources>    <string-array name="countries_array">        <item>Afghanistan</item>        <item>Albania</item>        <item>Algeria</item>        <item>American Samoa</item>        <item>Andorra</item>        <item>Angola</item>        <item>Anguilla</item>        <item>Antarctica</item>        ...    </string-array></resources>

    <3> In your activity or fragment, use the following code to specify the adapter that supplies the suggestions

// Get a reference to the AutoCompleteTextView in the layoutAutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);// Get the string arrayString[] countries = getResources().getStringArray(R.array.countries_array);// Create the adapter and set it to the AutoCompleteTextView ArrayAdapter<String> adapter =         new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);textView.setAdapter(adapter);

 

4. CheckBox

  Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list.

      

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent">    <CheckBox android:id="@+id/checkbox_meat"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/meat"        android:onClick="onCheckboxClicked"/>    <CheckBox android:id="@+id/checkbox_cheese"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/cheese"        android:onClick="onCheckboxClicked"/></LinearLayout>
public void onCheckboxClicked(View view) {    // Is the view now checked?    boolean checked = ((CheckBox) view).isChecked();        // Check which checkbox was clicked    switch(view.getId()) {        case R.id.checkbox_meat:            if (checked)                // Put some meat on the sandwich            else                // Remove the meat            break;        case R.id.checkbox_cheese:            if (checked)                // Cheese me            else                // I‘m lactose intolerant            break;        // TODO: Veggie sandwich    }}

 

5. Radio Button

  Radio buttons allow the user to select one option from a set

    

  because radio buttons are mutually exclusive, you must group them together inside a RadioGroup. By grouping them together,

    the system ensures that only one radio button can be selected at a time.

<?xml version="1.0" encoding="utf-8"?><RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="vertical">    <RadioButton android:id="@+id/radio_pirates"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/pirates"        android:onClick="onRadioButtonClicked"/>    <RadioButton android:id="@+id/radio_ninjas"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/ninjas"        android:onClick="onRadioButtonClicked"/></RadioGroup>
public void onRadioButtonClicked(View view) {    // Is the button now checked?    boolean checked = ((RadioButton) view).isChecked();        // Check which radio button was clicked    switch(view.getId()) {        case R.id.radio_pirates:            if (checked)                // Pirates are the best            break;        case R.id.radio_ninjas:            if (checked)                // Ninjas rule            break;    }}

 

6. Toggle Buttons

  A toggle button allows the user to change a setting between two states.

            (Switch. Android 4.0+)

<ToggleButton     android:id="@+id/togglebutton"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:textOn="Vibrate on"    android:textOff="Vibrate off"    android:onClick="onToggleClicked"/>
public void onToggleClicked(View view) {    // Is the toggle on?    boolean on = ((ToggleButton) view).isChecked();        if (on) {        // Enable vibrate    } else {        // Disable vibrate    }}

  or Using OnCheckedChangeListener

ToggleButton toggle = (ToggleButton) findViewById(R.id.togglebutton);toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {        if (isChecked) {            // The toggle is enabled        } else {            // The toggle is disabled        }    }});

 

7. Spinners

  Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value.

    Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.

    

<Spinner    android:id="@+id/planets_spinner"    android:layout_width="fill_parent"    android:layout_height="wrap_content" />

  7.1 Populate the Spinner with User Choices

//string resource file<?xml version="1.0" encoding="utf-8"?><resources>    <string-array name="planets_array">        <item>Mercury</item>        <item>Venus</item>        <item>Earth</item>        <item>Mars</item>        <item>Jupiter</item>        <item>Saturn</item>        <item>Uranus</item>        <item>Neptune</item>    </string-array></resources>
//in your activity or fragmentSpinner spinner = (Spinner) findViewById(R.id.spinner);// Create an ArrayAdapter using the string array and a default spinner layoutArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,        R.array.planets_array, android.R.layout.simple_spinner_item);// Specify the layout to use when the list of choices appearsadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);// Apply the adapter to the spinnerspinner.setAdapter(adapter);

  7.2 Responding to User Selection

public class SpinnerActivity extends Activity implements OnItemSelectedListener {    ...        public void onItemSelected(AdapterView<?> parent, View view,             int pos, long id) {        // An item was selected. You can retrieve the selected item using        // parent.getItemAtPosition(pos)    }    public void onNothingSelected(AdapterView<?> parent) {        // Another interface callback    }}

 

 

8. Picker

  Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs.

    

  <1>Extending DialogFragment for a time picker

public static class TimePickerFragment extends DialogFragment                            implements TimePickerDialog.OnTimeSetListener {    @Override    public Dialog onCreateDialog(Bundle savedInstanceState) {        // Use the current time as the default values for the picker        final Calendar c = Calendar.getInstance();        int hour = c.get(Calendar.HOUR_OF_DAY);        int minute = c.get(Calendar.MINUTE);        // Create a new instance of TimePickerDialog and return it        return new TimePickerDialog(getActivity(), this, hour, minute,                DateFormat.is24HourFormat(getActivity()));    }    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {        // Do something with the time chosen by the user    }}

  <2>Showing the time picker

Button     android:layout_width="wrap_content"     android:layout_height="wrap_content"    android:text="@string/pick_time"     android:onClick="showTimePickerDialog" />
public void showTimePickerDialog(View v) {    DialogFragment newFragment = new TimePickerFragment();    newFragment.show(getSupportFragmentManager(), "timePicker");}

5.User Interface/Input Controls