Пользовательский вид действия не может быть нажат - PullRequest
22 голосов
/ 27 марта 2011

Я пытаюсь добавить пользовательский ActionView к моему ActionBar.

Я пытаюсь добавить общую кнопку обновления. (ImageButton, ProgressBar внутри FrameLayout), но если я использую 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;
        }
    }
}
* Src код

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>

С другой стороны, если я установлю clickListener на ImageView внутри класса RefreshView, он будет вызван.

Кто-нибудь уже делал это?

Ответы [ 3 ]

8 голосов
/ 17 апреля 2011

onOptionsItemSelected() следует вызывать только в том случае, если элемент действия находится в меню переполнения, которое вы также должны обработать.(Вы должны принудительно «всегда» на панели действий, поэтому onOptionsItemSelected() не будет вызываться).

При onCreateOptionsMenu() после надувания необходимо установить OnMenuItemClickListener для пункта меню.

4 голосов
/ 17 апреля 2011

Я использовал код src от http://code.google.com/p/styled-action-bar/.

1 голос
/ 17 марта 2013

Я нашел рабочее решение для себя и хочу поделиться им с вами.Он основан на первом подходе (@Macarse) с некоторыми важными изменениями.

Важно: соответствующим образом адаптировать метод initView

  1. Установить onClickListener для ImageView ( mButton )

  2. Установите загрузку в true и сообщите активности ( MyActivity)) о клике

    private void initView(final Context context) {
        final LayoutInflater inflator = LayoutInflater.from(context);
    
        final View actionView = inflator.inflate(
                R.layout.action_refresh_progress, this);
        mProgressBar = (ProgressBar) actionView
                .findViewById(R.id.action_refresh_progress);
    
        mButton = (ImageView) actionView
                .findViewById(R.id.action_refresh_button);
    
        mButton.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(final View view) {
                setLoading(true);
                ((MyActivity) context).handleRefreshButtonClick();
            }
        });
    }
    
  3. Реакция в соответствии с кликом в действии ( MyActivity )

    public void handleRefreshButtonClick() {
        // Start refreshing...
    }
    

Я надеюсь, что мой подход может сэкономить вам время на поиск рабочего решения!

...