Başlığınızdan özel bir bileşen oluşturabilir ve 'onClick()' öğesini tanımlayabilirsiniz. Örneğin, RelativeLayout'u genişletecek ve header.xml'inizi buraya şişirecek yeni bir sınıf Header
yapın. Ardından, <include>
etiketi yerine <com.example.app.Header android:id="@+id/header" ...
kullanırsınız. Kod çoğaltması yok ve başlık tamamen yeniden kullanılabilir.
UPD:
<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 İşte bazı kod örnekleri
header.xml var :Bu örnekte
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() Başlığının kurucu içinde hareket edebilir, fakat genellikle bu yöntem bazı yararlı dinleyici aktarmak için iyi bir yol sağlar. Umarım bu yardımcı olur.
Bu kulağa hoş geliyor. Ama bunu nasıl yaparım? – rlc
Bir örnek ekledim. – Ash
Altbilgiyi hiç göremiyorum. aktivite dışı sınıftaki bir etkinliğin getSystemService() 'yöntemini kullanabilir miyiz? 'getContext()' ile denedim ama hiçbir şey göstermiyor. –