如何从开到关开关按钮图像,反之亦然后单击? [英] How to switch button image from on to off and vice versa upon click?

查看:236
本文介绍了如何从开到关开关按钮图像,反之亦然后单击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图从开到关,反之亦然切换我的按钮的状态,通过添加图像,并添加图像为关闭状态。我试图通过XML,但是我只是能在点击暂时切换(通过使用preSS /聚焦等)。这里是$ C $下是相同的:

I have been trying to switch the state of my buttons from on to off and vice versa, by adding an image for on and adding an image for off state. I tried through xml, however I was just able to temporarily switch it upon click (by using press/focus etc). Here is the code for the same:

fragment_justin:

fragment_justin:

<RelativeLayout
        android:id="@+id/top_bar_container"
        android:layout_width="match_parent"
        android:layout_height="48.5dp"
        android:layout_alignParentTop="true"
        android:background="@color/background_action_bar"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/menu_button"
            android:layout_width="30dp"
            android:layout_height="48.5dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@android:color/transparent"
            android:paddingRight="24dp"
            android:src="@drawable/overflow_btn" />

        <com.justin.abc.FontTextView
            android:id="@+id/most_recent_text"
            android:layout_width="wrap_content"
            android:layout_height="48.5dp"
            android:layout_marginLeft="11dp"
            android:layout_marginRight="2dp"
            android:textColor="@color/white"
            foo:customFont="Cabin-Bold.ttf"
            android:layout_alignParentLeft="true"
            android:textSize="18sp"
            android:gravity="center_vertical"
            android:text="@string/most_recent"/>

    </RelativeLayout>

聚焦刚上ImageButton的一部分,你会看到overflow_btn。现在overflow_btn是一类下抽拉叫,如下:

Focussing just on the imagebutton part,you'll see the overflow_btn. Now overflow_btn is a class called under drawable , as follows:

overflow_btn:

overflow_btn:

 <?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:state_enabled="false"
    android:drawable="@drawable/overflow_pressed" />
<item
    android:state_pressed="true"
    android:state_enabled="true"
    android:drawable="@drawable/overflow_pressed" />
<item
    android:state_focused="true"
    android:state_enabled="true"
    android:drawable="@drawable/overflow_pressed" />
<item
    android:state_enabled="true"
    android:drawable="@drawable/overflow" />
</selector>

当使用上述code,它暂时切换,只有当挖(如闪烁,以overflow_ pressed),并恢复到溢出按钮的状态。 我相信有可能是这种情况发生在java code需要做一些改变,因此这里是对应的Java类:

Upon using the above code, it temporarily switches the button states only when tapped ( like it flashes to overflow_pressed) and reverts back to overflow. I believe there might be some changes required in the java code for this to happen,Hence here's the corresponding java class :

@Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_justin, container, false);
        createMenus() ;
        setOnclickListeners(view);

        mAdapter = new CursorAdapter(getActivity(), null, 0);
        final ListView list = (ListView) view.findViewById(R.id.justin_list);
        list.setAdapter(mAdapter);
        list.setOnItemLongClickListener(this);
        list.setOnTouchListener(this);
        list.setOnItemClickListener(this);

        LayoutUtils.showLoading(view, R.id.justin_list);
        return view;
    }

    private void setOnclickListeners(final View view){
        final ImageButton button = (ImageButton) view.findViewById(R.id.menu_button);
        button.setOnClickListener(this);
    }

    private void createMenus() {
        mPreferenceMenuItems.add(PreferenceMenuItems.JUSTIN_PREFERENCES);
        mPreferencesMenuHelper = new MenuHelper(getActivity(), mPreferenceMenuItems,this);

        mDeleteMenuItems.add(DeleteMenuItems.DELETE_JUSTIN);
        mDeleteMenuHelper = new MenuHelper(getActivity(), mDeleteMenuItems,this);
    }

    @Override
    public void onResume() {
        super.onResume();
        final MainActivity activity = (MainActivity) getActivity();
        activity.updateActionBarTitle();
        final IntentFilter filter = new IntentFilter();
        activity.getApplicationContext().registerReceiver(mReceiver, filter);
    }

    @Override
    public void onPause() {
        getActivity().getApplicationContext().unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    public void onCursorLoaded(final Uri uri, final Cursor cursor) {
        if (cursor.getCount() > 0) {
            mAdapter.swapCursor(cursor);
            showResults(uri);
        } else {
            if (!isOperationExecuting()) {
                showNoResults(uri);
            }
        }
    }


    @Override
    public void onMenuItemClicked(final int position) {
        if (isPreferences) {
            switch (position) {
                case PreferenceMenuItems.JUSTIN_PREFERENCES_POSITION:
                    PreferencesActivity.newInstance(getActivity());
                    break;
                default:
                    break;
            }
            mPreferencesMenuHelper.hideMenu();
        } else {
            switch (position) {
                case DeleteMenuItems.DELETE_POSITION:
                    final DialogFragment dialog = new DeleteFromDialogFragment();
                    final Bundle bundle = new Bundle();
                    bundle.putString(JUSTIN_ID, mJustinID);
                    dialog.setArguments(bundle);
                    dialog.show(getFragmentManager(), DELETE_FROM_JUSTIN );
                    break;
                default:
                    break;
            }
            mDeleteMenuHelper.hideMenu();
        }
    }

    @Override
    public void onClick(final View view) {
        switch (view.getId()) {
            case R.id.justin_menu_button:
                final Activity activity = getActivity();
                final int actionBarHeight = activity.findViewById(R.id.title_main_container).getHeight();
                final int menuBarHeight = activity.findViewById(R.id.justin_top_bar_container).getHeight();
                mPreferencesMenuHelper.showMenu(actionBarHeight + menuBarHeight, Gravity.RIGHT, R.style.MenuDialogAnimation);
                isPreferences = true;

                break;
            default:
                break;
        }
    }

    @Override
    public void showResults(final Uri uri) {
        if (mIsAnimating) {
            mShouldShowResult = true;
        } else {
            LayoutUtils.showResults(getView(), R.id.justin_list);
            mShouldShowResult = false;
        }
    }

    @Override
    public void showNoResults(final Uri uri) {
        if (mIsAnimating) {
            mShouldShowNoResult  = true;
        } else {
            LayoutUtils.showNoResult(getView(), R.id.justin_list, getResources().getString(R.string.no_result));
            mShouldShowNoResult = false;
        }
    }

    @Override
    public void onOperationStarted(final Uri uri) {
        LayoutUtils.showLoading(getView(), R.id.justin_list);
    }

    @Override
    public boolean onItemLongClick(final AdapterView<?> adapter, final View view, final int position, final long id) {
        isPreferences = false;
        final Activity activity = getActivity();
        final int actionBarHeight = activity.findViewById(R.id.title_main_container).getHeight();
        final int menuBarHeight = activity.findViewById(R.id.justin_top_bar_container).getHeight();
        mDeleteMenuHelper.showMenu(mYValue + actionBarHeight + menuBarHeight, Gravity.CENTER, R.style.MenuDialogAnimation);

        final Cursor cursor = (Cursor) mAdapter.getItem(position);
        mJustinID = cursor.getString(cursor.getColumnIndex(Justin.Columns.ID));

        return false;
    }

    @Override
    public boolean onTouch(final View v, final MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            mYValue = (int)event.getY();
        }

        return false;
    }

    public void restartLoader(){
        getContentLoader().restartLoader();
    }

    @Override
    public void onItemClick(final AdapterView<?> adapter, final View view, final int position, final long id) {
        final Cursor cursor = (Cursor) mAdapter.getItem(position);
        if (!NetworkUtils.isOnline() && ContentProvider.isStoryEmty(cursor)) {
            final DialogFragment dialog = new CheckOfflineAccessDialogFragment();
            dialog.show(getFragmentManager(), OFFLINE_ACCESS);
            return;
        }

        final String documentSource = cursor.getString(cursor.getColumnIndex(Justin.Columns.SOURCE));
        final ArticlePagerFragment ArticlePagerFragment = ArticlePagerFragment.newInstance(getFragmentManager(), position, documentSource, false);
        ArticlePagerFragment.setFragment(this);

    }

    public static String getArticleID(final Cursor cursor) {
        final String documentLink = cursor.getString(cursor.getColumnIndex(Justin.Columns.DOCUMENT_LINK));
        final String documentType = cursor.getString(cursor.getColumnIndex(Justin.Columns.TYPE));
        final String source = cursor.getString(cursor.getColumnIndex(Justin.Columns.SOURCE));
        String articleID = "";
        if (source.equalsIgnoreCase(Justin.NEWS_SOURCE_VALUE) && documentType.equalsIgnoreCase(Justin.TEXT_TYPE)) {
            articleID = documentLink.substring(documentLink.lastIndexOf("storyId=")+8);
        }
        return articleID;
    }

不知道如何去差不多吗?

Any idea how to go about the same?

MenuHelper:

MenuHelper:

public class MenuHelper implements OnItemClickListener{

    private final Dialog mMenu;
    private final OnMenuItemClickedListener mMenuItemListener;
    private final ArrayAdapter<String> mAdapter;
    private final int MENU_ITEM_HEIGHT = 40; // Defined in res/layout/menu_item.xml

    private List<Boolean> enabledStates;

    public MenuHelper(final Context context, final List<String> menuItems, final OnMenuItemClickedListener menuItemListener) {
        mMenu = new Dialog(context);
        mMenu.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mMenu.setContentView(R.layout.menu_container);
        enabledStates = new ArrayList<Boolean>(menuItems.size());
        for(int i = 0; i < menuItems.size(); i++) {
            enabledStates.add(true);
        }

        final ListView menuList = (ListView) mMenu.findViewById(R.id.menu_list);
        mAdapter = new ArrayAdapter<String>(context, R.layout.menu_item, menuItems) {
            @Override
            public boolean isEnabled(int position) {
                return enabledStates.get(position);
            }

            @Override
            public boolean areAllItemsEnabled() {
                return false;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                if(enabledStates.get(position)) {
                    ((TextView) view).setTextColor(Application.getAppResources().getColor(R.color.white));
                } else {
                    ((TextView) view).setTextColor(Application.getAppResources().getColor(R.color.disabled_gray));
                }
                if (convertView == null) {
                    convertView = super.getView(position, convertView, parent);
                }

                // check for odd or even to set alternate colors to the row background
                if (position % 2 == 0) {
                    convertView.setBackgroundResource(R.drawable.oddcellcolor);
                } else {
                    convertView.setBackgroundResource(R.drawable.evencellcolor);
                }
                return convertView;
                //return view;
            }
        };
        menuList.setOnItemClickListener(this);
        menuList.setAdapter(mAdapter);
        mMenuItemListener = menuItemListener;
    }

    public void showMenu(final int yPosition, final int horizontalGravity) {
        showMenu(yPosition, horizontalGravity, R.style.MenuDialogAnimation);
    }

    public void setEnabled(int position, boolean isEnabled) {
        enabledStates.set(position, isEnabled);
        mAdapter.notifyDataSetChanged();
    }

    public void setEnabledAll(boolean isEnabled) {
        for(int ii = 0; ii < enabledStates.size(); ii++) {
            enabledStates.set(ii, isEnabled);
        }
        mAdapter.notifyDataSetChanged();
    }

    public int getMenuHeight() {
        if (mMenu != null) {
            return (int) (mAdapter.getCount() * MENU_ITEM_HEIGHT  / Application.getAppResources().getDisplayMetrics().density);
        } else {
            return -1;
        }
    }

    public void showMenu(final float yPosition, final int horizontalGravity, final int animation) {
        final Window window = mMenu.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        if (horizontalGravity != Gravity.CENTER) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }
        final WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.TOP | horizontalGravity;
        params.y = Math.round(yPosition);
        params.windowAnimations = animation;
        window.setAttributes(params);
        mMenu.show();
    }

    public void hideMenu() {
        mMenu.hide();
    }

    @Override
    public void onItemClick(final AdapterView<?> adapter, final View view, final int position, final long parent) {
        mMenuItemListener.onMenuItemClicked(position);
    }


}

谢谢! 贾斯汀

Thanks! Justin

推荐答案

因此​​,基本上,你必须编辑您的code如下(根据一些解决方案已经建议修改): Menuhelper: 公共类MenuHelper实现OnItemClickListener {

So basically, you have to edit your code as follows(modified based on some solutions already suggested): Menuhelper : public class MenuHelper implements OnItemClickListener {

private final Dialog mMenu;
ImageButton button;
private final OnMenuItemClickedListener mMenuItemListener;
private final ArrayAdapter<String> mAdapter;
private final int MENU_ITEM_HEIGHT = 40; // Defined in res/layout/menu_item.xml

private List<Boolean> enabledStates;

public MenuHelper(final Context context, final List<String> menuItems, final OnMenuItemClickedListener menuItemListener) {
    this(context, menuItems, menuItemListener, null);
}

public MenuHelper(final Context context, final List<String> menuItems, final OnMenuItemClickedListener menuItemListener, final Dialog.OnDismissListener dismissListener) {
    mMenu = new Dialog(context);
    mMenu.setOnDismissListener(dismissListener);
    mMenu.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mMenu.setContentView(R.layout.menu_container);
    enabledStates = new ArrayList<Boolean>(menuItems.size());
    for(int i = 0; i < menuItems.size(); i++) {
        enabledStates.add(true);
    }

    final ListView menuList = (ListView) mMenu.findViewById(R.id.menu_list);
    mAdapter = new ArrayAdapter<String>(context, R.layout.menu_item, menuItems) {
        @Override
        public boolean isEnabled(int position) {
            return enabledStates.get(position);
        }

        @Override
        public boolean areAllItemsEnabled() {
            return false;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            if(enabledStates.get(position)) {
                ((TextView) view).setTextColor(Application.getAppResources().getColor(R.color.white));
            } else {
                ((TextView) view).setTextColor(Application.getAppResources().getColor(R.color.disabled_gray));
            }
            if (convertView == null) {
                convertView = super.getView(position, convertView, parent);
            }

            // check for odd or even to set alternate colors to the row background
            if (position % 2 == 0) {
                convertView.setBackgroundResource(R.drawable.oddcellcolor);
            } else {
                convertView.setBackgroundResource(R.drawable.evencellcolor);
            }
            return convertView;
            //return view;
        }
    };
    menuList.setOnItemClickListener(this);
    menuList.setAdapter(mAdapter);
    mMenuItemListener = menuItemListener;
}

public void showMenu(final int yPosition, final int horizontalGravity) {
    showMenu(yPosition, horizontalGravity, R.style.MenuDialogAnimation);
}

public void setEnabled(int position, boolean isEnabled) {
    enabledStates.set(position, isEnabled);
    mAdapter.notifyDataSetChanged();
}

public void setEnabledAll(boolean isEnabled) {
    for(int ii = 0; ii < enabledStates.size(); ii++) {
        enabledStates.set(ii, isEnabled);
    }
    mAdapter.notifyDataSetChanged();
}

public int getMenuHeight() {
    if (mMenu != null) {
        return (int) (mAdapter.getCount() * MENU_ITEM_HEIGHT  / Application.getAppResources().getDisplayMetrics().density);
    } else {
        return -1;
    }
}

public void showMenu(final float yPosition, final int horizontalGravity, final int animation) {
    final Window window = mMenu.getWindow();
    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    if (horizontalGravity != Gravity.CENTER) {
        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }
    final WindowManager.LayoutParams params = window.getAttributes();
    params.gravity = Gravity.TOP | horizontalGravity;
    params.y = Math.round(yPosition);
    params.windowAnimations = animation;
    window.setAttributes(params);
    mMenu.show();
}

public void hideMenu() {
    mMenu.hide();
}

@Override
public void onItemClick(final AdapterView<?> adapter, final View view, final int position, final long parent) {
    mMenuItemListener.onMenuItemClicked(position);
}

} 这需要你的菜单帮手照顾,接下来你的另一主类: 导入这些2:

} that takes care of your menu helper, next your other main class: import these 2 :

import android.content.DialogInterface;
import android.app.Dialog;

改变你的工具扩展: OnItemLongClickListener,OnTouchListener,OnItemClickListener,Dialog.OnDismissListener (注意我加ondismisslistener这里) 此外,添加这个方法:

change your implements extension to : OnItemLongClickListener, OnTouchListener, OnItemClickListener, Dialog.OnDismissListener (note I added ondismisslistener here) Also, add this method:

@Override
    public void onDismiss(DialogInterface dialog) {
        button.setSelected(false);
    }

也修改下面两行,如下所示:

also modify the below 2 lines as shown:

mPreferencesMenuHelper = new MenuHelper(getActivity(), mPreferenceMenuItems, this, this);
mDeleteMenuHelper = new MenuHelper(getActivity(), mDeleteMenuItems, this, this);

有关的onclick code和onmenuitemsclick code,你可以遵循维克拉姆提出的code解决方案,而且必须很好地工作。

For the onclick code and onmenuitemsclick code, you can follow the code solution suggested by vikram, and it must work fine.

这篇关于如何从开到关开关按钮图像,反之亦然后单击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆