Android学习笔记_30_常用控件使用

     一、状态栏通知(Notification):

   如果需要查看消息,可以拖动状态栏到屏幕下方即可查看消息。发送消息的代码如下:

   public void sendNotice(View v){

        int icon=android.R.drawable.stat_notify_chat;

        //第一个参数为图标,第二个参数为标题,第三个为通知时间

          Notification notification = new Notification(icon, "通知", System.currentTimeMillis());

        notification.defaults = Notification.DEFAULT_SOUND;//发出默认声音

         //打开通知时要启动的activity

        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15901681812"));

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, 0);

        notification.setLatestEventInfo(this, "新消息", "时间到,请拨打电话", pendingIntent);

        notification.flags = Notification.FLAG_AUTO_CANCEL;//自动取消

         //获取通知管理器

         NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        manager.notify(11, notification);//第一个参数为自定义的通知唯一标识

   }

     二、对话框通知(Dialog Notification)

   当你的应用需要显示一个进度条或需要用户对信息进行确认时,可以使用对话框来完成。下面代码将打开一个如右图所示的对话框:

public void notifcation() {

        new AlertDialog.Builder(this)

                .setTitle("AlertDialog测试")

                .setCancelable(false)

                // 设置不能通过“后退”按钮关闭对话框

                .setMessage("AlertDialog学习?")

                .setPositiveButton("确认", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialoginterface, int i) {

                        Uri uri = Uri.parse("http://www.itcast.cn/");// 打开链接

                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);

                        startActivity(intent);

                    }

                })

                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();

                    }

                }).show();// 显示对话框

    }

     三、创建带单选项列表的对话框 

//下面代码将打开一个如右上图所示的选项列表对话框:

final String[] items = {"java", ".net", "php"};

new AlertDialog.Builder(SenderNotificationActivity.this).setTitle("选择语言")

    .setItems(items, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int item) {

                Toast.makeText(getApplicationContext(), items[item], 

        Toast.LENGTH_SHORT).show();

        }

    }).show();//显示对话框

//下面代码将打开一个如右下图所示的带单选框的列表对话框:

final String[] items = {"java", ".net", "php"};

new AlertDialog.Builder(SenderNotificationActivity.this).setTitle("选择语言")

.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {

     public void onClick(DialogInterface dialog, int item) {

            Toast.makeText(getApplicationContext(), items[item], 

        Toast.LENGTH_SHORT).show();

            dialog.cancel();

      }

}).show();//显示对话框

//setSingleChoiceItems()的第二个参数是设置默认选项,

选项索引从0开始,-1代表不选择任何选项。

 

     四、创建带多选项列表的对话框

final String[] items = {"java", ".net", "php"};

new AlertDialog.Builder(SenderNotificationActivity.this).setCancelable(false)

.setTitle("选择语言")

.setMultiChoiceItems(items, new boolean[]{false,true,false}, new DialogInterface.OnMultiChoiceClickListener() {

    @Override

    public void onClick(DialogInterface dialog, int which, boolean isChecked) {

        if(isChecked){

        Toast.makeText(getApplicationContext(), items[which], 

            Toast.LENGTH_SHORT).show();

        }

        }

    })

.setPositiveButton("确认",

    new DialogInterface.OnClickListener(){

    public void onClick(DialogInterface dialoginterface, int i){

        dialoginterface.dismiss();

     }

})

.show();//显示对话框

 

     五、进度条

   使用代码ProgressDialog.show(ProgressDialogActivity.this, "请稍等", "数据正在加载中...", true);创建并显示一个进度对话框。

  调用setProgressStyle()方法设置进度对话框风格。有两种风格:

       ProgressDialog.STYLE_SPINNER 旋体进度条风格 (为默认风格)

       ProgressDialog.STYLE_HORIZONTAL 横向进度条风格

<!--在布局xml文件中添加进度条代码:-->

<ProgressBar 

    android:layout_width="fill_parent" 

    android:layout_height="20px"

    style="?android:attr/progressBarStyleHorizontal"

    android:id="@+id/downloadbar"/> 



<!--在代码中操作进度条:

         ProgressBar.setMax(100);//设置最大刻度

         ProgressBar.setProgress(0);//设置进度条的当前刻度,如果进度条的最大刻度为100,当前刻度为50,进度条将进行到一半。

-->

 

 

public class ProgressDialogActivity extends Activity {

private ProgressDialog progressDialog;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.menu); 

        //开始一条专门处理耗时工作的线程

        new Thread(new Runnable(){

            @Override

            public void run() {

               try {

                   Thread.sleep(5*1000);//假设这项工作需要5秒才能完成

                      progressDialog.dismiss();//关闭进程对话框

                     //runOnUiThread(finishDialog);//要求运行在UI线程

           } catch (InterruptedException e) {}

            }

        }).start();        

        progressDialog = ProgressDialog.show(ProgressDialogActivity.this, "请稍等", "数据正在加载中...", true);

   }    

   private Runnable finishDialog = new Runnable() {

        @Override

        public void run() {           

            progressDialog.dismiss();

        }

   };

}

 

     六、单选框(RadioButton)

要完成单选框显示,我们需要使用到RadioGroup和RadioButton(单选框),RadioGroup用于对单选框进行分组,相同组内的单选框只有一个单选框能被选中。(例子代码请见下方备注栏)

 RadioGroup.check(R.id.dotNet);将id名为dotNet的单选框设置成选中状态。

(RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());//获取被选中的单选框。

RadioButton.getText();//获取单选框的值

调用setOnCheckedChangeListener()方法,处理单选框被选择事件,把RadioGroup.OnCheckedChangeListener实例作为参数传入

  界面设计:

界面设计:

<?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"

    >

<RadioGroup android:id="@+id/radioGroup"

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="wrap_content"

  android:layout_height="wrap_content">

<RadioButton android:id="@+id/java"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="java" />

    <RadioButton android:id="@+id/dotNet"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="dotNet" />

    <RadioButton android:id="@+id/php"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="PHP" />

</RadioGroup>

</LinearLayout>

  处理程序

public void onCreate(Bundle savedInstanceState) {

        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); 

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            public void onCheckedChanged(RadioGroup group, int checkedId) {

                RadioButton radioButton = (RadioButton) findViewById(checkedId);

                Log.i(TAG, String.valueOf(radioButton.getText()));

            }

        });

}

 

     七、多选框(CheckBox)

  每个多选框都是独立的,可以通过迭代所有多选框,然后根据其状态是否被选中再获取其值。

  CheckBox.setChecked(true);//设置成选中状态。
  CheckBox.getText();//获取多选框的值
  调用setOnCheckedChangeListener()方法,处理多选框被选择事件,把CompoundButton.OnCheckedChangeListener实例作为参数传入。

 界面设计:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="wrap_content"

  android:layout_height="fill_parent">

  <CheckBox android:id="@+id/checkboxjava"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="java" />

  <CheckBox android:id="@+id/checkboxdotNet"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="dotNet" />

  <CheckBox android:id="@+id/checkboxphp"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:text="PHP" />

    

    <Button android:id="@+id/checkboxButton"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:text="获取值" />

</LinearLayout>

代码处理

public class CheckBoxActivity extends Activity {

    private static final String TAG = "CheckBoxActivity";

    private List<CheckBox> checkboxs = new ArrayList<CheckBox>();



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        checkboxs.add((CheckBox) findViewById(R.id.checkboxdotNet));

        checkboxs.add((CheckBox) findViewById(R.id.checkboxjava));

        checkboxs.add((CheckBox) findViewById(R.id.checkboxphp));

        checkboxs.get(1).setChecked(true);// 设置成选中状态

        for (CheckBox box : checkboxs) {

            box.setOnCheckedChangeListener(listener);

        }

        Button button = (Button) findViewById(R.id.checkboxButton);

        button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                List<String> values = new ArrayList<String>();

                for (CheckBox box : checkboxs) {

                    if (box.isChecked()) {

                        values.add(box.getText().toString());

                    }

                }

                Toast.makeText(CheckBoxActivity.this, values.toString(), 1).show();

            }

        });

    }



    private CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {

        @Override

        public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {

            CheckBox checkBox = (CheckBox) buttonView;

            Log.i(TAG,"isChecked=" + isChecked + ",value=" + checkBox.getText());// 输出单选框的值

        }

    };

}

 

     八、下拉列表框(Spinner)

  Spinner.getItemAtPosition(Spinner.getSelectedItemPosition());//获取下拉列表框的值,

      //调用setOnItemSelectedListener()方法,处理下拉列表框被选择事件,把AdapterView.OnItemSelectedListener实例作为参数传入。

  1、Spinner的界面设计:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="fill_parent"

  android:layout_height="wrap_content">

  <Spinner android:id="@+id/spinner"

      android:layout_height="wrap_content"

      android:layout_width="fill_parent"/>

</LinearLayout>

代码处理:

public class SpinnerActivity extends Activity {

    private static final String TAG = "SpinnerActivity";



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner);

        // 第二个参数为下拉列表框每一项的界面样式,该界面样式由Android系统提供,当然您也可以自定义

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

                android.R.layout.simple_spinner_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        adapter.add("java");

        adapter.add("dotNet");

        adapter.add("php");

        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override

            public void onItemSelected(AdapterView<?> adapterView, View view,

                    int position, long id) {

                Spinner spinner = (Spinner) adapterView;

                String itemContent = (String) adapterView.getItemAtPosition(position);

                Log.i(TAG, itemContent+" : "+spinner);

            }



            @Override

            public void onNothingSelected(AdapterView<?> view) {

                Log.i(TAG, view.getClass().getName());

            }

        });

    }

}

  很多时候显示在下拉列表框的值并不是希望得到的值,如果要做一个联系人下拉列表框,列表框列出的是联系人的姓名,因为姓名有可能相同,所以我们希望得到的值应该为该联系人的id,要实现这种需求我们需要自定义Adapter,当然自定义Adapter需要我们编写一小段代码,如果我们不想编写Adapter,又能实现我们的需求,那是最好不过的了。通过观察ArrayAdapter中getView(int position, View convertView, ViewGroup parent)的内部代码发现,如果为ArrayAdapter指定的实际泛型参数类型没有实现CharSequence(字符串)接口,将会调用该类型对象的toString()向下拉列表框输出显示值。利用这个特点我们可以重写javaBean的toString()向下拉列表框提供显示值。

   2、通过有没有实现CharSequence接口,来改变下拉列表框的显示值

public class SpinnerActivity extends Activity {

    private static final String TAG = "SpinnerActivity";

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner); 

        ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this, android.R.layout.simple_spinner_item);         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        adapter.add(new Person(12, "李明"));

        adapter.add(new Person(100, "李明"));

        adapter.add(new Person(62, "张天"));

        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override

    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {

        Spinner spinner = (Spinner)adapterView;

        Person person = (Person)adapterView.getItemAtPosition(position);

    }

    @Override

    public void onNothingSelected(AdapterView<?> view) {

        Log.i(TAG,  view.getClass().getName());

    }

        });

    }

}

Person.java

Person.java:

public class Person {

    private Integer id;

    private String name;

    

    public Person(Integer id, String name) {

        this.id = id;

        this.name = name;

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    @Override

    public String toString() {

        return name;

    }

}

  3、自定义下拉列表框样式:

    3.1下拉列表框每一项的界面样式:stylespinner.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"

   android:id="@+id/contentTextView"

    android:layout_width="fill_parent" 

    android:layout_height="wrap_content" 

    android:background="#F4FDFF"

    />

    3.2代码处理

public class SpinnerActivity extends Activity {

    private static final String TAG = "SpinnerActivity";

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.spinner); 

         //第二个参数为layout文件在R文件的id,第三个参数为TextView在layout文件的id

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.stylespinner, R.id.contentTextView);         adapter.add("java");

        adapter.add("dotNet");

        adapter.add("php");

        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

    @Override

    public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {

        Spinner spinner = (Spinner)adapterView;

        String itemContent = (String)adapterView.getItemAtPosition(position);

    }

    @Override

    public void onNothingSelected(AdapterView<?> view) {

        Log.i(TAG,  view.getClass().getName());

    }

        });

    }

}

 

     九、拖动条(SeekBar)

   SeekBar.getProgress()获取拖动条当前值

  调用setOnSeekBarChangeListener()方法,处理拖动条值变化事件,把SeekBar.OnSeekBarChangeListener实例作为参数传入。

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >



    <SeekBar

        android:id="@+id/seekBar"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" />



    <Button

        android:id="@+id/seekBarButton"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="获取值" />



</LinearLayout>
public class MainActivity extends Activity {

    private SeekBar seekBar;



    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.seekbar);

        seekBar = (SeekBar) findViewById(R.id.seekBar);

        seekBar.setMax(100);// 设置最大刻度

        seekBar.setProgress(30);// 设置当前刻度

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override

            public void onProgressChanged(SeekBar seekBar, int progress,

                    boolean fromTouch) {

                Log.v("onProgressChanged()", String.valueOf(progress) + ", "

                        + String.valueOf(fromTouch));

            }



            @Override

            public void onStartTrackingTouch(SeekBar seekBar) {// 开始拖动

                Log.v("onStartTrackingTouch()",

                        String.valueOf(seekBar.getProgress()));

            }



            @Override

            public void onStopTrackingTouch(SeekBar seekBar) {// 结束拖动

                Log.v("onStopTrackingTouch()",

                        String.valueOf(seekBar.getProgress()));

            }

        });

        

        Button button = (Button) this.findViewById(R.id.seekBarButton);

        button.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                Toast.makeText(MainActivity.this,

                        String.valueOf(seekBar.getProgress()), 1).show();

            }

        });

    }

}

     十、菜单(Menu)

   1、重写Activity的onCreateOptionsMenu(Menu menu)方法,该方法用于创建选项菜单,在用户按下手机的“Menu”按钮时就会显示创建好的菜单,在onCreateOptionsMenu(Menu menu)方法内部可以调用Menu.add()方法实现菜单的添加。

  2、重写Activity的onMenuItemSelected()方法,该方法用于处理菜单被选择事件。通过手机上提供的“MENU”按钮可以打开菜单,如果希望通过代码打开菜单,可以调用Activity的openOptionsMenu()方法。

public class MenuActivity extends Activity {

private static final String TAG = "MenuActivity";

private static final int MENU_ADD = Menu.FIRST;

private static final int MENU_UPDATE = Menu.FIRST + 1;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.menu); 

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

    menu.add(Menu.NONE, MENU_ADD, Menu.NONE, "添加");  

    menu.add(Menu.NONE, MENU_UPDATE, Menu.NONE, "更新");

    return super.onCreateOptionsMenu(menu);

    }

    @Override

    public boolean onMenuItemSelected(int featureId, MenuItem item) {

    switch (item.getItemId()) {

      case MENU_ADD:

           Log.i(TAG, "add was selected");

           return true;

      case MENU_UPDATE:

           Log.i(TAG, "update was selected");

           return true;

      default:

              return super.onMenuItemSelected(featureId, item);

      }

    }    

}

 

     十一、自动完成文本框(AutoCompleteTextView)

   AutoCompleteTextView和EditText组件类似,都可以输入文本。但AutoCompleteTextView组件可以和一个字符串数组或List对

绑定,当用户输入两个及以上字符时,系统将在AutoCompleteTextView组件下方列出字符串数组中所有以输入字符开头的字符串,这一点和www.google.com的搜索框非常相似,当输入某一个要查找的字符串时,google搜索框就会列出以这个字符串开头的最热门的搜索字符串列表。

<AutoCompleteTextView



   android:layout_width="fill_parent“  android:layout_height="wrap_content“



  <!-- completionThreshold 指定至少输入几个字符后才会出现自动提示功能-->

   android:completionThreshold="1“ 



   android:id="@+id/name" />
public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  String[] names = {"abcd", "wers", "123a", "123s" , "sfsf", "sss", "abc", "acc"};

  AutoCompleteTextView nameText = (AutoCompleteTextView)this.findViewById(R.id.name);

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, names);

  nameText.setAdapter(adapter);



}

  除了AutoCompleteTextView控件外,我们还可以使用MultiAutoCompleteTextView控件来完成连续输入的功能。也就是说,当输入完一个字符串后,在该字符串后面输入一个逗号(,),在逗号前后可以有任意多个空格,然后再输入一个字符串,仍然会显示自动提示列表。

  使用MultiAutoCompleteTextView时,需要为它的setTokenizer方法指定MultiAutoCompleteTextView.CommaTokenizer类对象实例,该对象表示采用逗号作为输入多个字符串的分隔符。

< MultiAutoCompleteTextView

   android:layout_width="fill_parent“  android:layout_height="wrap_content“

  <!– completionThreshold 指定至少输入几个字符后才会出现自动提示功能à

   android:completionThreshold="1“ 

   android:id="@+id/name" />

 

public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

     String[] names = {"abcd", "wers", "123a", "123s" , "sfsf", "sss", "abc", "acc"};
     MultiAutoCompleteTextView nameText = (MultiAutoCompleteTextView)this.findViewById(R.id.name);

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,    names);

     nameText.setAdapter(adapter);

     nameText.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());}

 

你可能感兴趣的:(Android学习)