例如:
public abstract class BaseTitleFragment extends BaseFragment { TitleBar mTitleBar; @Override protected int getLayoutId() { return R.layout.fragment_base_title; } @Override protected void onBindViewBefore(View root) { super.onBindViewBefore(root); // on before onBindViewBefore call ViewStub stub = (ViewStub) root.findViewById(R.id.lay_content); stub.setLayoutResource(getContentLayoutId()); stub.inflate(); } @Override protected void initWidget(View root) { super.initWidget(root); // not null mTitleBar = (TitleBar) root.findViewById(R.id.nav_title_bar); mTitleBar.setTitle(getTitleRes()); mTitleBar.setIcon(getIconRes()); mTitleBar.setIconOnClickListener(getIconClickListener()); } protected abstract @LayoutRes int getContentLayoutId(); protected abstract @StringRes int getTitleRes(); protected @DrawableRes int getIconRes() { return 0; } }
其中@LayoutRes、@StringRes 、@DrawableRes 就是对int类型的约束,返回符合我们具体要求的int类型值,这就实现了我们需要的是int类型的资源id,而不是一个普通的int类型值
public void init(@DrawableRes int resId, @StringRes int strId, Class clx) { mIconView.setImageResource(resId); mTitleView.setText(strId); mClx = clx; mTag = mClx.getName(); }
这样int就不在是一个单纯的int类型值,而是一个资源id,通过这个资源id来给我们的控件设置数据