安卓介面進階組件------拖動條和評星條,安卓------拖動
一 拖動條
安卓手機音量設定都是給出一個拖動條,使得使用者能夠拖動滑塊進行設定,這裡我們介紹拖動條。
安卓拖動條控制項是繼承自ProgressBar控制項,所以它能夠支援ProgressBar的xml屬性。但是他有自己的獨特屬性:
android:max 設定最大的拖動兩
android:progress 設定初始化進度
android:thumb 設定滑塊圖形
事件監聽方面,拖動條需要注意:我們不在監聽使用者的點擊操作,而是監聽滑塊的改變,下面用一個執行個體簡單的操作一下拖動條。
執行個體:介面上給出一個拖動條和文本,滑動滑塊文本動態顯示
1.建立工程,在布局檔案中加入一個文本和拖動條。這裡我設定了當前進度值和滑塊圖形
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="112dp" android:text="當前進度:0" /> <SeekBar android:id="@+id/seekBar1" android:thumb="@drawable/penguin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" /> </RelativeLayout>
2.代碼中擷取文本和拖動條,給拖動條加監聽器。監聽器內部控制了文本的動態顯示。監聽有三個方法,注意:改寫一下開始和結束滑動的方法,另外一個和是否是使用者滑動有關,我們且不去管它
tv = (TextView)findViewById(R.id.textView1); sb = (SeekBar)findViewById(R.id.seekBar1); sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar s) { final int p = s.getProgress(); tv.setText("當前進度:" + p); }//結束滑動 @Override public void onStartTrackingTouch(SeekBar s) { tv.setText("正在拖動!"); }//開始滑動 @Override public void onProgressChanged(SeekBar s, int arg1, boolean arg2) { } });
運行代碼,滑動滑塊,能夠看到文本根據滑動動態顯示內容。
二 評星條
很多視屏軟體和是應用市場軟體都有評星的功能,這是的評分應用情境是:拖動評星條,之後點擊某個提交按鈕完成評分。這裡我們簡單看一下評星條的屬性,之後類比一個類似的評星功能。
android:isIndicator 表明是指標,也就是能不能被使用者評分,值為"true"不能被改變
android:numStars 評星條的星星總數
android:rating 評星條的預設星級
android:stepSize 評星一次變化的分量,預設狀態下為0.5,使用者一次拖動改變0.5的星級
執行個體:做一個簡單的評分介面
1.建立工程,布局中加入顯示文本,評星條,提交按鈕
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="184dp" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/ratingBar1" android:layout_centerHorizontal="true" android:layout_marginBottom="100dp" android:text="評分:" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/ratingBar1" android:layout_centerHorizontal="true" android:text="提交" /> </RelativeLayout>
2.在主Activity裡面執行個體化顯示文本,評星條,按鈕
tv = (TextView)findViewById(R.id.textView1); asb = (RatingBar)findViewById(R.id.ratingBar1); b = (Button)findViewById(R.id.button1);
3.給按鈕加監聽事件,擷取評星條的評分,顯示到文本中去。評星的擷取通過getRating()方法
b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final float r; r = asb.getRating(); tv.setText("評分"+ r +"星"); } });
運行代碼,效果如下:
希望自己能寫出通俗易懂的文章,希望大家留言評論!