点击按钮如何在开启和关闭状态之间切换图片?

3

我一直在尝试通过添加开启和关闭状态的图片来切换按钮的状态,从而实现开启和关闭之间的切换。我尝试使用XML来实现,但是只能在单击时临时切换它(通过使用press/focus等)。以下是相应的代码:

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是drawable下的一个类,如下所示:
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>

使用以上代码后,它只在被点击时暂时切换按钮状态(就像闪烁到overflow_pressed),然后恢复为overflow状态。我认为可能需要对Java代码进行一些更改才能实现这一点,因此这里是相应的Java类:
@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;
    }

有什么办法可以处理同样的问题吗?

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);
    }


}

感谢您! 贾斯汀
5个回答

4

我同意@Chronos的看法,这更像是一个有两种状态的ToggleButton。保持简单,这是我的示例xml,你可以用作参考。不需要代码,只需要xml。

这是我的布局xml:

<ToggleButton
        android:id="@+id/btnHeadache"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:background="@drawable/headache_button"
        android:paddingTop="25sp"
        android:text="@string/headache"
        android:textOn=""
        android:textOff="" />

现在这是各州的xml,当然是在我的drawable文件夹中与图片一起。如果上面不清楚,它的名称是headache_button.xml。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/check"  android:state_checked="true"/> <!-- currently pressed turning the toggle on -->
    <item android:drawable="@drawable/headache" android:state_checked="false" /> <!-- currently pressed turning the toggle off   -->
</selector>

1
如果我理解得没错的话,您需要一个 ToggleButton,即带有两种状态的按钮。
然后使用像这样的选择器:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_normal" android:state_checked="false"/>
    <item android:drawable="@drawable/btn_pressed" android:state_checked="true"/>

</selector>

0

您可以在代码中使用以下方法来实现:

// Declare button
// Set its original background image
button.setBackground(getResources().getDrawable(R.drawable.original_button_image));

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        // Choose whichever image for pressed state
        v.setBackground(getResources().getDrawable(R.drawable.button_is_pressed)); 

        new Handler().postDelayed(new Runnable() {

            public void run() {

                v.setBackground(getResources().getDrawable(R.drawable.original_button_image));

                // Button Click Code Here
            }

        }, 100L);    // Change this value to whatever is suitable

    }

});

编辑 1:

<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:src="@drawable/testdrawable"
        android:paddingRight="24dp" />

由于按钮只有两种状态,建议尝试使用testdrawable代替您在问题中发布的那个:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/overflow_pressed" />
    <item 
        android:drawable="@drawable/overflow" />
</selector>

将你的 onClick(View) 改为:

@Override
public void onClick(final View view) {
    switch (view.getId()) {
        case R.id.justin_menu_button:

            if (button.isSelected()) {
                button.setSelected(false);
                isPreferences = false;
                mPreferencesMenuHelper.hideMenu();
                Log.i("ImageButtonCheck", "Button is not selected anymore");
            } else {
                button.setSelected(true);
                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;
                Log.i("ImageButtonCheck", "Button is in selected state");
            }

            break;
        default:
            break;
    }
}

onMenuItemClicked(int)更改为:

@Override
public void onMenuItemClicked(final int position) {
    if (isPreferences) {
        switch (position) {
            case PreferenceMenuItems.JUSTIN_PREFERENCES_POSITION:
                PreferencesActivity.newInstance(getActivity());
                break;
            default:
                break;
        }
        isPreferences = false;
        button.setSelected(false);
        mPreferencesMenuHelper.hideMenu();
        Log.i("ImageButtonCheck", "Button is not in a selected state because of a menu item click");
    } 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();
    }
}

我认为这里的问题在于,当首次按下按钮时,会达到所选状态并显示菜单。但是,在菜单显示时再次点击按钮不会调用onClick(View)方法。我在上面的代码中包含了3个日志语句。当您单击一次按钮以显示菜单,然后再次单击菜单以隐藏它时,请告诉我在logcat中看到的输出。这两次点击的输出应该是"Button is in selected state""Button is not selected anymore"

编辑2:

MenuHelper作为内部类包含在您的活动类中:

public class MenuHelper implements OnItemClickListener, Dialog.OnDismissListener {

    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);
        mMenu.setOnDismissListener(this);  -------------------------> **add this**
        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);
    }

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

}

我已经这样做了,但现在每次我第二次点击按钮时,菜单就会消失(如预期),应用程序崩溃。 - user2386226
@JusticeBauer 你能分享一下代码吗?如果我有它的话,调试会更容易。 - Vikram
没问题,已经完成了,感谢您的帮助,您能否看一下这个问题:http://stackoverflow.com/questions/17956135/how-do-i-fix-a-moving-checkbox 并且看看是否能够帮忙解决它? - user2386226
你有关于这个问题的任何想法吗:http://stackoverflow.com/questions/18382510/how-do-i-fix-the-password-username-authentication-in-my-code/18428135?noredirect=1#18428135 - user2386226

0

听起来你应该使用复选框。普通的按钮没有“开”状态,只有按下和焦点。使用复选框,你需要使用 android:state_checked="true"。点击复选框将会切换到选中状态,再次点击则会切换回默认状态(未选中)。

在确定无法使用 XML 解决问题之前,请尽量不要添加额外的 Java 代码。


1
我需要将图像切换为另一个,这是完全可能的,与复选框无关。 - user2386226
你有没有关于这个问题的任何想法:http://stackoverflow.com/questions/18382510/how-do-i-fix-the-password-username-authentication-in-my-code/18428135?noredirect=1#18428135 - user2386226

0

如果我理解正确,您想要一个具有两种状态的“按钮”,并且点击它可以在这两种状态之间切换。

在这种情况下,看起来更像是您想要一个“ToggleButton”、“CompoundButton”或“Switch”的行为。您可以使用“android:state_checked”在xml中配置它们,如@Chronos所述。


它对第一个有效,但我在哪里添加view.setEnabled(true);,以便再次单击时它会恢复到原始图像? - user2386226
好的,所以你想让按钮有响应。我会考虑一下并在明天或之后纠正我的答案。 - Neil Townsend
好的,就我所看到的,第一个 view.setEnabled(false); 已经可以正常工作了,只是想知道我需要在哪里设置什么,以便在每次点击后它可以恢复到原始状态。 - user2386226
更像是一个开关图像。 - user2386226
你对这个问题有任何线索吗? - user2386226
我的笔记本电脑坏了,而且我离家十天,但我会尽快补充答案,抱歉耽搁了。 - Neil Townsend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接