你可以在你的頭文件之外製作一個自定義組件,並在其中定義'onClick()'。例如,創建一個新的類Header
,它將擴展一個RelativeLayout並在其中擴展header.xml。然後,代替<include>
標籤,您可以使用<com.example.app.Header android:id="@+id/header" ...
。沒有代碼重複和頭成爲完全可重用。
UPD:下面是一些代碼示例
header.xml:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="@+id/logo" .../>
<TextView android:id="@+id/label" .../>
<Button android:id="@+id/login" .../>
</merge>
activity_with_header.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" ...>
<com.example.app.Header android:id="@+id/header" .../>
<!-- Other views -->
</RelativeLayout>
Header.java:
public class Header extends RelativeLayout {
public static final String TAG = Header.class.getSimpleName();
protected ImageView logo;
private TextView label;
private Button loginButton;
public Header(Context context) {
super(context);
}
public Header(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Header(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void initHeader() {
inflateHeader();
}
private void inflateHeader() {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.header, this);
logo = (ImageView) findViewById(R.id.logo);
label = (TextView) findViewById(R.id.label);
loginButton = (Button) findViewById(R.id.login);
}
ActivityWithHeader.java :
public class ActivityWithHeader extends Activity {
private View mCreate;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_with_header);
Header header = (Header) findViewById(R.id.header);
header.initHeader();
// and so on
}
}
在這個例子中,Header.initHeader()可以報頭的構造內移動,但一般這種方法提供了一個很好的方式來傳遞一些有用的監聽器。希望這會有所幫助。
來源
2011-09-14 19:27:17
Ash
聽起來不錯。但我該怎麼做? – rlc
我已經添加了一個例子。 – Ash
我根本看不到頁腳。我們可以在非活動類中調用「getSystemService()」方法嗎?我嘗試'getContext()',但它不顯示任何東西。 –