Bạn có thể tạo thành phần tùy chỉnh ra khỏi tiêu đề của mình và xác định 'onClick()' trong đó. Ví dụ: tạo một lớp mới Header
để mở rộng RelativeLayout và tăng tệp header.xml của bạn ở đó. Sau đó, thay vì thẻ <include>
bạn sẽ sử dụng <com.example.app.Header android:id="@+id/header" ...
. Không sao chép mã và tiêu đề trở nên hoàn toàn có thể tái sử dụng được.
UPD: Dưới đây là một số ví dụ mã
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
}
}
Trong ví dụ này, Header.initHeader() có thể được di chuyển bên trong constructor Tiêu đề, nhưng nhìn chung phương pháp này cung cấp một cách tốt đẹp để vượt qua trên một số thính giả hữu ích. Hy vọng điều này sẽ giúp.
Nghe hay đấy. Nhưng làm thế nào để tôi làm điều đó? – rlc
Tôi đã thêm một ví dụ. – Ash
tôi không thể thấy chân trang nào cả. chúng ta có thể gọi phương thức 'getSystemService()' của một hoạt động trong lớp không hoạt động không ?. tôi đã thử với 'getContext()' nhưng nó không hiển thị bất cứ thứ gì. –