Android常用控件
下拉列表
代码如下:
final String[] dataSource = new String[]{"Item 1", "Item 2", "Item 3"};
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataSource));
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("用户的选择是:"+dataSource[position]);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
-----------------------------------------------------------------------------------------------------
日期选择
代码:
final Calendar c = Calendar.getInstance();
final Button btnChooseDte = (Button) findViewById(R.id.btnChooseDate);
btnChooseDte.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DatePickerDialog(ChooseADate.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String theDate = String.format("%d-%d-%d", year, monthOfYear + 1, dayOfMonth);
System.out.println(theDate);//手机App选择4月,系统会输出3,所以要+1
btnChooseDte.setText(theDate);
}
},c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();//c.get(Calendar.MONTH)实际会比月份小1
}
});
}
-------------------------------------------------------------------------------------------------------------------------------------------
时间选择
final Button btnChooseTime = (Button) findViewById(R.id.btnChooseTime);
btnChooseTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new TimePickerDialog(ChooseTime.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String theTime = String.format("%d:%d",hourOfDay,minute);
System.out.println(theTime);
btnChooseTime.setText(theTime);
}
},0,0,true).show();
}
});
-------------------------------------------------------------------------------------------------------------------
单项选择
代码
xml中主要控件是RadioGroup和RadioButton
final RadioButton rbA = (RadioButton) findViewById(R.id.rbA); findViewById(R.id.btnSubmit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (rbA.isChecked()){ Toast.makeText(SingleChoose.this,"所选是正确的",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(SingleChoose.this,"所选是错误的",Toast.LENGTH_SHORT).show(); } } });
多项选择
public class MulChoose extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener { private CheckBox cb1, cb2, cb3, cb4; private TextView tvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mul_choose); cb1 = (CheckBox) findViewById(R.id.cb1); cb2 = (CheckBox) findViewById(R.id.cb2); cb3 = (CheckBox) findViewById(R.id.cb3); cb4 = (CheckBox) findViewById(R.id.cb4); tvResult = (TextView) findViewById(R.id.tvResult); cb1.setOnCheckedChangeListener(this); cb2.setOnCheckedChangeListener(this); cb3.setOnCheckedChangeListener(this); cb4.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { String str = ""; if (cb1.isChecked()){ str+=cb1.getText()+" "; } if (cb2.isChecked()){ str+=cb2.getText()+" "; } if (cb3.isChecked()){ str+=cb3.getText()+" "; } if (cb4.isChecked()){ str+=cb4.getText(); } tvResult.setText(str); } }
Toast
Toast toast = Toast.makeText(MainActivity.this,"显示一个带有图片的Toast",Toast.LENGTH_LONG); ImageView imageView = new ImageView(MainActivity.this); imageView.setImageResource(R.mipmap.ic_launcher); toast.setView(imageView); toast.setGravity(Gravity.CENTER,0,500); toast.show();
Notification
public class MainActivity extends AppCompatActivity { public static final int NOTIFICATION_ID = 1200; private int counter = 0; private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { counter++; NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this); builder.setSmallIcon(R.mipmap.ic_launcher);//图标 builder.setContentTitle("您有"+counter+"条短消息!");//主要标题 builder.setContentText("123456789!");//消息主体 Notification notification = builder.build(); NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(NOTIFICATION_ID, notification);//mID allows you to update the notification later on. } }); } }
自动完成输入框 AutoCompleteTextView:
<AutoCompleteTextView android:id="@+id/autoCompleteTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="1" android:textColor="@android:color/black" /> <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:completionThreshold="1" android:textColor="@android:color/black" />
android:completionThreshold="1"表示输入多少个字母开始提示。
1 package com.zhang.autocompletetextview; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.widget.ArrayAdapter; 6 import android.widget.AutoCompleteTextView; 7 import android.widget.MultiAutoCompleteTextView; 8 9 10 public class MainActivity extends AppCompatActivity { 11 12 private AutoCompleteTextView autoCompleteTextView; 13 private MultiAutoCompleteTextView multiAutoCompleteTextView; 14 private ArrayAdapter<String> autoAdapter,multiAutoAdapter;//adapter是一样的 15 private String[] strs = new String[]{ 16 "Hello", 17 "Hello Java", 18 "Hello C++", 19 "Hello Android"}; 20 21 @Override 22 protected void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 setContentView(R.layout.activity_main); 25 26 autoAdapter = new ArrayAdapter<>(this, R.layout.simple_dropdown_item,strs); 27 autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView); 28 autoCompleteTextView.setAdapter(autoAdapter); 29 30 multiAutoAdapter = new ArrayAdapter<>(this, R.layout.simple_dropdown_item, strs); 31 multiAutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView); 32 multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); 33 multiAutoCompleteTextView.setAdapter(multiAutoAdapter); 34 35 36 } 37 }
ProgressBar:
<ProgressBar style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar1" /> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar2" /> <ProgressBar style="?android:attr/progressBarStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/progressBar3" /> <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/progressBar" android:indeterminate="false" />
1 package com.zhang.uicontrols; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.widget.ProgressBar; 6 7 import java.util.Timer; 8 import java.util.TimerTask; 9 10 public class AtyUsingProgressBar extends AppCompatActivity { 11 12 private ProgressBar progressBar; 13 14 @Override 15 protected void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.activity_aty_using_progress_bar); 18 19 progressBar = (ProgressBar) findViewById(R.id.progressBar); 20 21 22 // progressBar.setMax(100); 23 // 24 // progressBar.setProgress(50); 25 26 new Thread(new Runnable() { 27 @Override 28 public void run() { 29 30 int progressMax = progressBar.getMax(); 31 32 while (progressMax != progressBar.getProgress()){ 33 int stepProgress = progressMax/10; 34 int currentPro = progressBar.getProgress(); 35 progressBar.setProgress(currentPro+stepProgress); 36 try { 37 Thread.sleep(1000); 38 } catch (InterruptedException e) { 39 e.printStackTrace(); 40 } 41 } 42 } 43 }).start(); 44 } 45 46 @Override 47 protected void onResume() { 48 super.onResume(); 49 // startTimer(); 50 } 51 52 @Override 53 protected void onPause() { 54 super.onPause(); 55 // stopTimer(); 56 } 57 58 private int progress = 0; 59 60 public void startTimer() { 61 if (timer == null) { 62 timer = new Timer(); 63 task = new TimerTask() { 64 @Override 65 public void run() { 66 progress++; 67 progressBar.setProgress(progress); 68 } 69 }; 70 timer.schedule(task, 1000, 1000); 71 } 72 73 } 74 75 public void stopTimer() { 76 if (timer != null) { 77 task.cancel(); 78 timer.cancel(); 79 80 task = null; 81 timer = null; 82 } 83 } 84 85 private Timer timer = null; 86 private TimerTask task = null; 87 }
SeekBar:
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/tvOut" /> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/seekBar" />
1 package com.zhang.uicontrols; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.widget.SeekBar; 6 import android.widget.TextView; 7 8 public class AtyUsingSeekBar extends AppCompatActivity { 9 10 private SeekBar seekBar; 11 private TextView tvOut; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_aty_using_seek_bar); 17 18 tvOut = (TextView) findViewById(R.id.tvOut); 19 seekBar = (SeekBar) findViewById(R.id.seekBar); 20 seekBar.setMax(100); 21 22 seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 23 @Override 24 public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 25 tvOut.setText(String.format("当前的进度为:%d",progress)+"%"); 26 } 27 28 @Override 29 public void onStartTrackingTouch(SeekBar seekBar) { 30 31 } 32 33 @Override 34 public void onStopTrackingTouch(SeekBar seekBar) { 35 36 } 37 }); 38 } 39 }
ProgressDialog:
1 package com.zhang.uicontrols; 2 3 import android.app.ProgressDialog; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 8 public class AtyUsingProgressDialog extends AppCompatActivity { 9 10 private ProgressDialog progressDialog; 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_aty_using_progress_dialog); 16 17 findViewById(R.id.btnShowProgressDialog).setOnClickListener(new View.OnClickListener() { 18 @Override 19 public void onClick(View v) { 20 progressDialog = ProgressDialog.show(AtyUsingProgressDialog.this, "加载中", "正在加载,请稍后"); 21 22 new Thread(){ 23 @Override 24 public void run() { 25 super.run(); 26 try { 27 sleep(3000); 28 progressDialog.dismiss(); 29 30 } catch (InterruptedException e) { 31 e.printStackTrace(); 32 } 33 } 34 }.start(); 35 } 36 }); 37 } 38 }
RatingBar:
<RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ratingBar" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" />
1 package com.zhang.uicontrols; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.widget.RatingBar; 6 import android.widget.Toast; 7 8 public class AtyUsingRatingBar extends AppCompatActivity { 9 10 private RatingBar ratingBar; 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_aty_using_rating_bar); 16 17 ratingBar = (RatingBar) findViewById(R.id.ratingBar); 18 ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { 19 @Override 20 public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { 21 Toast.makeText(getApplicationContext(),"评价为"+rating,Toast.LENGTH_SHORT).show(); 22 } 23 }); 24 25 } 26 }
ImageSwitcher:
<ImageSwitcher android:id="@+id/imageSwitcher" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_centerHorizontal="true" android:layout_centerVertical="true" />
1 package com.jikexueyuan.uicontrols; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.view.animation.AnimationUtils; 7 import android.widget.ImageSwitcher; 8 import android.widget.ImageView; 9 import android.widget.ViewSwitcher; 10 11 public class AtyUsingImageSwitcher extends AppCompatActivity { 12 13 private ImageSwitcher imageSwitcher; 14 private boolean showImg1 = true; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_aty_using_image_switcher); 20 21 imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher); 22 imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() { 23 @Override 24 public View makeView() { 25 return new ImageView(AtyUsingImageSwitcher.this); 26 } 27 }); 28 29 //动画效果 30 imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(AtyUsingImageSwitcher.this,android.R.anim.fade_in)); 31 imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(AtyUsingImageSwitcher.this, android.R.anim.fade_out)); 32 33 imageSwitcher.setOnClickListener(new View.OnClickListener() { 34 @Override 35 public void onClick(View v) { 36 showImg1 = !showImg1; 37 showCurrentImg(); 38 } 39 }); 40 showCurrentImg(); 41 } 42 43 private void showCurrentImg(){ 44 if (showImg1){ 45 imageSwitcher.setImageResource(R.drawable.image_a); 46 } else { 47 imageSwitcher.setImageResource(R.drawable.image_b); 48 } 49 } 50 }