Android基礎控制項(EditView、SeekBar等)的使用方法_Android

來源:互聯網
上載者:User

 android提供了大量的UI控制項,本文將介紹TextView、ImageView、Button、EditView、ProgressBar、SeekBar、ScrollView、WebView的使用方法。在介紹各種控制項之前,先簡單介紹android UI控制項最基本的幾種屬性:

id: id是控制項唯一識別碼,可通過**findViewById(R.id.*)**操作控制項。
layout_width:控制項寬度,可設定為match_parent(充滿父布局,即讓父布局決定當前控制項的寬度)、wrap_content(恰好包住裡面的內容)、具體值(一般以dp作為單位)。
layout_width:控制項高度,可設定為match_parent、wrap_content、具體值。
visibility:可見與否,有三個可選值:visible(可見,不設定該屬性為預設值)、invisible(透明,仍在螢幕上佔據空間)、gone(不可見,不佔據空間)。
1.TextView(文本)

TextView可以說是最簡單的控制項了。

1.1 基本屬性

<!--res/layout/activity_main.xml--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical">   <TextView    android:id="@+id/text"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:gravity="center"    android:textSize="30sp"    android:textColor="#334433"    android:text="@string/app_name"    /> </LinearLayout>

text: text屬性即顯示出來的文字,@string/app_name表示引用資源檔res/values/strings.xml中的app_name,也可以直接寫內容。

<!--res/values/strings.xml--><resources>  <string name="app_name">UIExample</string>  <string name="title_activity_main">MainActivity</string></resources>

gravity: 對TextView中內容位置的設定,可選值為top、bottom、left、right、center等。可以為多個值,例如希望文字位於該TextView的右下角,設定為gravity="right|bottom",用 | 隔開
textSize與textColor 文字大小與顏色。
id: 這裡用了"\@+id/text",表示給id分配一個唯一識別碼text,與引用類似,多了一個+。
1.2 定義style

    假如上面的樣式是標題的樣式,且被重複使用多次。如果每個標題都這樣定義樣式,不但增加工作量,而且會使用修改變得很困難,這種情況下,將style抽象出來能解決這個問題。
    這與Web開發中CSS的作用如出一轍。

<!--res/values/styles.xml 增加TextTitle--><resources>  ...  <style name="TextTitle">    <item name="android:textColor">#334433</item>    <item name="android:textSize">30sp</item>    <item name="android:gravity">center</item>  </style></resources> <!--res/layout/activity_main.xml 將TextView作如下修改即可-->  <TextView    android:id="@+id/text"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="@string/app_name"    style="@style/TextTitle"    />

1.3 動態操作

// 使用代碼動態設定TextView中的常值內容public class MainActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    // 通過findViewById,擷取TextView的執行個體。    // 使用setText()與getText()賦值和取值。    TextView textView = (TextView) findViewById(R.id.text);    textView.setText("Hello World!");    Log.d("MainActivity",textView.getText().toString());  }}

2.ImageView(圖片)

有文本,自然少不了圖片。

<ImageView  android:id="@+id/image"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:src="@drawable/test_image"  />

id: 若不在java代碼中動態操作,id屬性可以省略。
src: 即定義顯示的圖片,將需要載入的圖片放置在 res/drawable/目錄下即可。

// 調用setImageResource()方法即可。// 需要載入的圖片複製到 res/drawable/ 目錄下。ImageView imageView = (ImageView) findViewById(R.id.image);imageView.setImageResource(R.drawable.test_image2);

3.Button(按鈕)

3.1 基本樣式

<Button  android:id="@+id/button_1"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:text="I Am A Button"  />

text: text即按鈕上的提示內容
3.2 點擊事件

3.2.1 為點擊事件註冊監聽器

// 第12行,註冊監聽器OnClickListener,複寫onClick()函數。public class MainActivity extends Activity {   private TextView textView;     @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    textView = (TextView) findViewById(R.id.text);    Button button = (Button) findViewById(R.id.button_1);    button.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        // ... 省略點擊事件        // 例如:textView.setText("Hello World");      }    });  }}

3.2.2 實現介面OnClickListener

// 第14行,將點擊事件綁定到 this// 第17行,複寫介面OnClickListener的onClick()方法// java中只能繼承一個類,介面可以看作java的多繼承方式public class MainActivity extends Activity implements View.OnClickListener{   private TextView textView;     @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    textView = (TextView) findViewById(R.id.text);    Button button = (Button) findViewById(R.id.button_1);    button.setOnClickListener(this);  }     @Override  public void onClick(View view){    // 根據id判斷,若一個活動中有多個控制項需綁定點擊事件    // 使用該方式,該方法簡潔直觀    switch (view.getId()){      case R.id.button_1:        // ... 省略點擊事件        // 例如:textView.setText("Hello World!");        break;      default:        break;    }  }}

4.EditText(輸入框)

4.1 基本樣式

<EditText  android:id="@+id/edit"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:maxLines="3"  android:hint="Please Input..."  />

maxLines: 指定輸入框的最大行號為3行,超過3行後,文本將向上滾動,EditText不會繼續被展開。如果不指定,EditText將隨著輸入內容的增加而被展開。
hint: 類似Html中的placeholder,用於輸入框的提示。
4.2 擷取輸入內容

// 點擊按鈕,列印輸入的內容。public class MainActivity extends Activity {     @Override  protected void onCreate(Bundle savedInstanceState) {    // ...    Button button = (Button) findViewById(R.id.button_1);    final EditText editText = (EditText) findViewById(R.id.edit);    button.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        // 使用 getText()方法擷取editText的內容        String input_text = editText.getText().toString();        Log.d("MainActivity",input_text);      }    });  }}

5.ProgressBar(進度條)

5.1 圓形進度條

<ProgressBar  android:id="@+id/progress_bar"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:visibility="gone"  />

visibility: visible(可見)、invisible(透明,佔據空間)、gone(不可見,不佔據空間),初始值設定為不可見。

// 一般比較耗時的工作,會暫時顯示進度條,工作完成後,進度條消失// 以下代碼類比該過程public class MainActivity extends Activity implements View.OnClickListener{   private ProgressBar progressBar;   @Override  protected void onCreate(Bundle savedInstanceState) {    // ...    Button button = (Button) findViewById(R.id.button_1);    progressBar = (ProgressBar) findViewById(R.id.progress_bar);    button.setOnClickListener(this);  }   @Override  public void onClick(View view) {    switch (view.getId()){      case R.id.button_1:        // 點擊按鈕後,如果目前狀態可見,則變為不可見        // 如不可見,則變為可見        if(progressBar.getVisibility() == View.GONE) {          progressBar.setVisibility(View.VISIBLE);        } else {          progressBar.setVisibility(View.GONE);        }        break;      default: break;    }  }}

5.2 水平進度條

<ProgressBar  android:id="@+id/progress_bar"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:max="100"  style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"  />

style: 設定style為水平樣式,其他樣式可以自己嘗試。

// 將onClick() 改為@Overridepublic void onClick(View view) {  switch (view.getId()){    case R.id.button_1:      // 擷取當前進度值,每次點擊進度值+10      int progress = progressBar.getProgress();      progressBar.setProgress(progress + 10);    default: break;  }}

6.SeekBar(滑動條)

6.1 基本樣式

<SeekBar  android:id="@+id/seek_bar"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:max="100"  android:progress="50"  /><TextView  android:id="@+id/text"  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:gravity="center"  />

max: 滑動條的最大值,設定為 100
progress: 初始化滑動條的值,設定為 50
6.2 註冊滑動監聽器

public class MainActivity extends Activity {   private TextView textView;     @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    textView = (TextView) findViewById(R.id.text);    SeekBar seekBar = (SeekBar) findViewById(R.id.seek_bar);    // 設定滑動監聽器,複寫三個事件函數,分別是值改變、開始滑動、結束滑動    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {      @Override      public void onProgressChanged(SeekBar seekBar, int progress,           boolean fromUser) {        if(fromUser){          // 使用者主動滑動,值改變時觸發該事件          textView.setText("使用者正在滑動,當前值:" + progress);        }      }       @Override      public void onStartTrackingTouch(SeekBar seekBar) {        Log.d("MainActivity","開始滑動時觸發該事件");      }       @Override      public void onStopTrackingTouch(SeekBar seekBar) {        Log.d("MainActivity","結束滑動時觸發該事件");      }    });  }}

7.SrollView(可滾動視圖)

<ScrollView  android:layout_width="wrap_content"  android:layout_height="wrap_content">  <!-- ... 省略其他控制項-->  <TextView    android:id="@+id/text"    android:layout_width="match_parent"    android:layout_height="wrap_content"    /></ScrollView>

當TextView的內容過多時(一頁顯示不完),這時使用ScrollView可以使頁面變為可垂直滾動模式,垂直滾動看完所有內容。
8.WebView(瀏覽器)

<WebView  android:id="@+id/web_view"  android:layout_width="match_parent"  android:layout_height="match_parent"  />

在AndroidManifest.xml中加入訪問網路的許可權

<manifest ... >  <application ...>    ...  </application>  <uses-permission android:name="android.permission.INTERNET"/></manifest>
public class MainActivity extends Activity {   @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    WebView webView = (WebView) findViewById(R.id.web_view);    // 允許執行javasript    webView.getSettings().setJavaScriptEnabled(true);    // 設定代理,複寫shouldOverrideUrlLoading函數    webView.setWebViewClient(new WebViewClient(){      @Override      public boolean shouldOverrideUrlLoading(WebView view,String url){        view.loadUrl(url); //載入網頁        return true; //true表示使用當前WebView開啟網頁,不使用系統瀏覽器      }    });    webView.loadUrl("http://www.jb51.net");  }}

運行程式,類似於一個開啟了網頁的瀏覽器,只是缺少網址輸入框。

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.