Android實戰之複用一返回導航欄

在實際項目開發中,不少界面元素都是類似的,我們可以提取出來,根據具體需求加以稍微的改變就可以實現複用,實現了功能同時也減少了代碼量。

     比如,返回導航欄就是非常通用的界面模塊,我們可以定義一個xml,包含返回按鈕,以及textview標籤顯示當前頁面的描述。然後,在需要使用返回導航欄目的地方include進去就可以了。

    複用的xml代碼很簡單,就是一個button和textview元素。 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="@dimen/padding44"
                android:background="@color/orange" >

    <Button
        android:background="@drawable/navi_btn_selector"
        android:id="@+id/btn_navitest_back"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/padding15"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"


        android:textColor="@color/white"
        android:textSize="@dimen/text_size_15" />

    <TextView
        android:typeface="sans"
        android:id="@+id/navi_title_test"
        android:layout_centerInParent="true"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_14"
        android:text="主頁"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>
他的界面效果如圖:

                                 

那麼如何在頁面使用複用的xml並讓返回按鈕生效、以及讓“主頁”更加業務場景發生改變呢。很簡單,先在頁面xml中包含進通用的xml,然後在Activity中通過findViewById找到他們,然後實例化,並給按鈕設置監聽器,給textView設置文字setText。例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_color"
    android:orientation="vertical">

    <include layout="@layout/a_test_custom_navi_bar"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/padding2"
        android:background="@color/white"
        android:clickable="true"
        android:orientation="horizontal"
        android:padding="4dp">

        <ImageView
            android:id="@+id/iv_state_detail"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:src="@mipmap/fail"/>

代碼沒寫完整,其實就在頂部include進去就好。  然後是Activity中的代碼:

		setContentView(R.layout.state_details_activity);
		tv_topic_navi = (TextView)findViewById(R.id.navi_title_test);
		tv_topic_navi.setText(R.string.topic_detail);
		tv_topic_navi.setTextSize(17);

		btn_topic_back = (Button)findViewById(R.id.btn_navitest_back);

		btn_topic_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				StateItemDetailActivity.this.finish();
			}
		});






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章