布局文件中可以设置android:tag和android:id
<android.support.v7.widget.RecyclerView
     android:id="@+id/recycler"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:background="#F7F7F7"
     android:tag="recycler"
     android:nestedScrollingEnabled="false"
     android:overScrollMode="never">
代码中通过id或者tag找到控件
RecyclerView mRecycler = (RecyclerView) findViewById(R.id.recycler);
View tag = mLayout.findViewWithTag("recycler");
另一种花式获取控件id的方法
// R.id.recycler
findViewById(getResources().getIdentifier("recycler", "id", getPackageName()));
// R.layout.linear_layout
findViewById(getResources().getIdentifier("linear_layout", "layout", getPackageName()));

通过使用tag方便自定义第三方库的时候 侵入性非常低的找到自己需要操作的控件
腾讯bugly自动升级源码中有使用到tag自定义升级弹框布局 比id更为灵活

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐