Set the Button state and keep it after onClick
I'm not sure this is even possible. I have this button:
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="45px"
android:drawableTop="@drawable/buttontv"
android:layout_weight="1"
android:background="@null"
android:textColor="#ffffff"
android:textSize="9px"
android:text="TV"/>
And this button has this item xml:
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="false"
android:drawable="@drawable/tv" />
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/tv_pressed" />
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/tv_pressed" />
<item
android:drawable="@drawable/tv" />
</selector>
And in my application I use this code for when clicking my button:
OnClickListener b1Listener = new OnClickListener(){
@Override
public void onClick(View v) { loadUrl("http://example.org/"); v.setPressed(true); }
};
开发者_如何学JAVA Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(b1Listener);
What I would like that when I have pressed the button, the drawableTop sets to one of the items with the @drawable/tv_pressed attribute value - and stays there (as in 'this is the currently active button').
I tried adding v.setPressed(true) in the onClick function (as this was all I could find with Google) but that didn't work.
Can this be done? Or is there a better alternative to what I'm trying to accomplish?
If you need a button that gets pressed and stays active, use a ToggleButton
https://stackoverflow.com/a/9750125/1257369
button.setFocusable(true);
button.setFocusableInTouchMode(true);///add this line
or with styles.xml
<item name="android:focusable">true</item>
<item name="android:focusableInTouchMode">true</item>
as mentioned above by the answer, it is ideal to use a togglebutton but if you are using a listview in this scenario, then the togglebutton will block out your listview's setOnItemClickListener. You can fix that issue as well by adding the descendants as blocked in the listview layout. However some people have reported that even then, their listview items won't click after using toggle buttons.
Are you working with dialogs/dialogfragments? This code might help you if you are, because i had a simmilar problem and this worked for me. :)
1- extend your class with DialogFragment ,Override Onstart() method.
@Override
public void onStart() {
super.onStart();
final AlertDialog D = (AlertDialog) getDialog();
if (D != null) {
Button positive = (Button) D.getButton(Dialog.BUTTON_POSITIVE);
positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (edittext.equals("")) {
Toast.makeText(getActivity(), "EditText empty don't close",Toast.LENGTH_SHORT).show();
} else {
D.dismiss(); //dissmiss dialog
}
}
});
}}
精彩评论