我正在尝试将自定义的ActionView
添加到我的ActionBar
中。
我想添加一个常见的刷新按钮(ImageButton
,在FrameLayout
中使用ProgressBar
),但是如果我使用了ActionView
,onOptionsItemSelected()
从未被调用。
以下是代码:
在我的Activity
中:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.messages_actionbar, menu);
mRefreshView = (RefreshView) menu.findItem(R.id.messages_refresh).getActionView();
return super.onCreateOptionsMenu(menu);
}
messages_actionbar
的来源:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/messages_refresh"
android:title="title"
android:icon="@drawable/icon"
android:showAsAction="always"
android:actionViewClass="com.blabla.RefreshView"/>
</menu>
RefreshView
的代码:
public class RefreshView extends FrameLayout {
private ImageView mButton;
private ProgressBar mProgressBar;
private boolean mLoading;
public RefreshView(Context context) {
super(context, null);
initView(context);
}
public RefreshView(Context context, AttributeSet attrs) {
super(context, attrs, 0);
initView(context);
}
public RefreshView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
private void initView(Context context) {
LayoutInflater inflator = LayoutInflater.from(context);
View v = inflator.inflate(R.layout.actionbar_refresh, this);
mProgressBar = (ProgressBar) v.findViewById(R.id.action_refresh_progress);
mButton = (ImageView) v.findViewById(R.id.action_refresh_button);
}
public void setLoading(boolean loading) {
if (loading != mLoading) {
mProgressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
mButton.setVisibility(loading ? View.GONE : View.VISIBLE);
mLoading = loading;
}
}
}
actionbar_refresh
的源代码:
<?xml version="1.0" encoding="utf-8" ?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/action_refresh_button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:scaleType="center"
android:background="@drawable/icon" />
<ProgressBar
android:id="@+id/action_refresh_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
android:indeterminate="true" />
</FrameLayout>
另一方面,如果我在RefreshView
类内部为其中的ImageView
设置了一个clickListener
,那么它将被调用。
有人已经这样做过了吗?
menu.findItem(R.id.messages_refresh).getActionView();
返回正确的视图。如果您所说的是正确的,那么Gmail应用程序是如何做到的呢?您认为他们设置了clickListener
,然后自定义视图以某种方式通知了Activity
吗? - MacarseonOptionsItemSelected()
吗?如果是这样,你如何区分它们? - CommonsWare