我无法获取工具栏中的 Framelayout 或 Textview 的 Id。请看一下:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorAppBg"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/logo"/>
<FrameLayout
android:id="@+id/fl_message_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="right|center">
<ImageView
android:id="@+id/iv_cart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginRight="12dp"
android:layout_marginTop="2dp"
android:src="@drawable/envelope"/>
<TextView
android:id="@+id/tv_message_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|right"
android:text="10"
android:textColor="@color/colorWhite"
android:gravity="center"
android:textSize="12sp"
android:visibility="visible"
android:background="@drawable/circle_notification"/>
</FrameLayout>
</FrameLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
这是我在 fragment 或扩展 AppCompatActivity 的 Activity 中查找这些 View ID 的代码。 内部 fragment :
`private Activity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.activity =(Activity)context;
}
flMessageCountBg = (FrameLayout) activity.findViewById(R.id.fl_message_bg);`
Activity 中:
FrameLayout flMessageCountBg = (FrameLayout) findViewById(R.id.fl_message_bg);
在这两种情况下我都得到空值。请帮助我解决这个问题。提前致谢。
最佳答案
您正在使用支持库,因此您应该将工具栏设置为支持操作栏。然后您可以使用 toolbar.findviewbyid(id)
获取工具栏中的 ViewToolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView iv = (ImageView) toolbar.findViewById(R.id.iv_cart);
如果您使用的是 fragment 并且您的 Activity 扩展了 AppCompatActivity,那么您可以按如下方式设置支持操作栏:
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
关于Android : Error in getting id of any view created inside android. support.v7.widget.Toolbar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436910/