Вы можете сделать собственный компонент из своего заголовка и определить в нем '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 () можно перемещать внутри конструктора Header, но обычно этот методобеспечивает хороший способ передать некоторых полезных слушателей.Надеюсь, это поможет.