1. 程式人生 > 實用技巧 >第四天啦

第四天啦

今天學了,四大布局,還有如何自定義佈局,和引入自定義佈局,還有自定義控制元件,最後就是ListView 最後這個ListView學的迷迷糊糊,還有什麼介面卡,嘔吼是我Java沒學好吧emmm。

程式碼

佈局

四大布局

引入自定義佈局 (UICustomViews)

  1. 自定義標題欄佈局 新建一個佈局檔案title.xml


<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:background="#000000"
android:text="back"
android:textColor="#fff" />

<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:gravity="center"
android:text="Title Text"
android:textColor="#fff"
android:textSize="24sp"/>

<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center"
android:background="#000000"
android:text="Edit"
android:textColor="#fff"/>
  • 在需要的佈局檔案中用<include layout = "”/>來引入自定義標題欄佈局.

<include layout="@layout/title"/>
  • 用自定義標題欄時需要把系統自帶的隱藏起來,因此用到getSupportActionBar()方法來獲取ActionBar的例項,然後呼叫hind()方法將預設的標題欄隱藏起來即可。

自定義控制元件

  • 新建一個類並繼承LinearLayout,並重寫其中兩個帶引數的建構函式,以便在佈局中引入該控制元件時呼叫建構函式。

public class TitleLayout extends LinearLayout {


public TitleLayout(Context context, AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);

}}
  • 在建構函式中用LayouInflater 對標題欄佈局進行動態載入,然後呼叫from()方法構建出一個LayoutInflater物件,後呼叫inflate()方法載入一個動態佈局檔案

  • inflate() 方法帶兩個引數,第一個引數是要載入佈局的id 第二個引數是給載入好的佈局新增一個父佈局

  • 在佈局中新增控制元件需要指明控制元件完整類名,包名。

  • 然後可用像正常控制元件那樣設定監聽

ListView(ListViewTest)

ListView的簡單用法

   private String[] data = {"Apple","Banana", "hello", "nice to eet you", "good morning",
"ambition", "stranger","Apple","Banana", "hello", "nice to eet you", "good morning",
"ambition", "stranger","Apple","Banana", "hello", "nice to eet you", "good morning",
"ambition", "stranger"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,data);
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);
}

  • ListView是用來展示大量資料的

  • 陣列中的資料無法直接的傳遞給ListView,所以要藉助介面卡,藉助ArrayAdapter,他可用通過泛型來指定適配的資料型別,然後在建構函式中將要適配資料傳入。

  • 建構函式中一共有三個函式,第一個是上下文,第二個是ListView子項佈局的id,現在用 android.R.layout.simple_list_item_1 作為ListView子項的id,第三個是要適配的資料。

  • android.R.layout.simple_list_item_1是Android內建的佈局檔案,裡面只有一個TextView,可用於簡單的顯示一段文字。

  • 最後用ListView 的setAdapter()方法,將構建好的介面卡物件傳遞進去

自定義ListView介面

英語

  • type n. 型別,品種;模範;樣式

  • margin n. 邊緣;利潤,餘裕;頁邊的空白

  • context n.環境,上下文