How to use the Spinner control in Android Studio 2-2

3 Modify the color of TextView through Spinner

Next, implement the following functions through the Spinner control, as shown in Figure 6.
 
 
Figure 6 Modify the color of TextView through Spinner
Change the content displayed in the TextView to the corresponding color by selecting the color corresponding to the subitem of the Spinner.

3.1 Setting layout

Create a layout in LinearLayout through the following code.
 
 
Figure 7 Layout file code

3.2 Add a sub-item selection listener for the Spinner control

Next, add a sub-item selection listener for the Spinner control. When the user clicks a sub-item of the Spinner control, the listener will be activated. The code is shown in Figure 8.
 
 
Figure 8 The Spinner subitem selects the listener

sp1 is the variable associated with the Spinner control mentioned in "2.1 Associated Controls", through which the setOnItemSelectedListener() method is called to set the sub-item selection listener of the Spinner control. The parameter of the setOnItemSelectedListener() method is a variable of the AdapterView.OnItemSelectedListener class, which specifies a callback function. When the user clicks a sub-item of the Spinner control, the Andorid system will call the callback function specified by the variable. The AdapterView.OnItemSelectedListener class has two public callback methods (Figure 8②), in which when the user clicks on a sub-item, the onItemSelected() function will be called (Figure 8③); when the sub-item list disappears, onNothingSelected will be called ()function.

When the user clicks a sub-item, the system will call the onItemSelected() function shown in Figure 8②. The parameter adapterView of this function indicates which view is selected by the user, here adapterView refers to the Spinner control; the variable view indicates the sub-item selected by the user; the variable i indicates the index value of the selected sub-item; the variable l indicates the selected The row ID of the child.

3.3 Select the listener add function for sub-items

In the onItemSelected() function, use the switch...case statement to judge the parameters, and the code is shown in Figure 9.

Figure 9 Different options are processed differently

Among them, tv1 is an object of the TextView class, and has been associated with the TextView control in Figure 7. Call the setTextColor() function of the TextView class through tv1 to set the color of the text in the TextView control, and the effect is shown in Figure 10.

Figure 10 Modify TextView color

Guess you like

Origin blog.csdn.net/hou09tian/article/details/127588097