Android remove button dynamically - android

I have a button and when I press it, i want to remove it (not make it invisible). I read that I can do that using layout.removeView(mybutton) but what is the layout ? and how can I get it in my activity
Button showQuestion;
private void initialize() {
showQuestion = (Button) findViewById(R.id.bAnswerQuestionShowQuestion);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bAnswerQuestionShowQuestion:
showQuestion.setVisibility(View.INVISIBLE);
//Here i want to delete the button
question.setVisibility(View.VISIBLE);
theAnswer.setVisibility(View.VISIBLE);
answerQuestion.setVisibility(View.VISIBLE);
showChoices.setVisibility(View.VISIBLE);
showHint.setVisibility(View.VISIBLE);
break;
}
}

see link
ViewGroup layout = (ViewGroup) button.getParent();
if(null!=layout) //for safety only as you are doing onClick
layout.removeView(button);

i have a button and when i press it , i want to remove it (not make it
invisible)
=> You did as below:
showQuestion.setVisibility(View.INVISIBLE);
Try with:
showQuestion.setVisibility(View.GONE);
FYI, INVISIBLE just hide the view but physically present there and GONE hide as well remove the presence physically as well.

You can use
button.setVisibility(View.GONE);

Layout is the parent Layout of your Button, usually a RelativeLayout or LinearLayout.
You can get it as follows:
ViewParent layout = button.getParent();

Related

100 Buttons and only 1 Active

I have one activity and here i have 100 buttons, i want that when i press Button 1 then press another Button the Button 1 should get unpressed.
i know i can make this with
if(Button1.isPressed()) {
Button2.setPressed(false);
Button3.setPressed(false);
Button4.setPressed(false);
Button5.setPressed(false);
Button6.setPressed(false);
Button7.setPressed(false);
Button8.setPressed(false);
......................... }
else { do nothing }
.... BUT!
it's too much code
Coders will kill me or will just laugh on me.
any ideas?
maybe there is a way to unpress the all buttons from the activity?
Not the prettiest solution ever, but you could make an OnClickListener like this:
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
ViewGroup parent = (ViewGroup) v.getParent();
for (int i = 0; i < parent.getChildCount(); i++) {
View current = parent.getChildAt(i);
if (current != v && current instanceof Button) {
((Button) current).setPressed(false);
}
}
((Button) v).setPressed(true);
}
}
and attach it to all of your buttons.
Then, whenever a button is clicked, it will iterate over all views that are in the same layout (or actually, view group) as the clicked button, and, for any of those views that are buttons except for the clicked button, it will call setPressed(false).
Note that this only works out of the box if all the buttons are in the same layout. If they are in nested layouts, you will have to adapt it a little.
Off topic: What do you need 100 buttons for? That's a lot of buttons. You may want to redesign your user interface
Ok so instead of looping through all the buttons on over and over again when one button is pressed, you can just store a variable which stores the button number of the button that was last pressed. Now, when the second button is pressed, disable the button that was pressed earlier, you get its index from the saved variable, enable the button that was pressed and store its index in the variable.
Heres an example pseudo code to give you and idea:
int buttonLastPressed = 0;
void onButtonClick(Button buttonPressed){
if(buttonLastPressed != 0){
disableButton(buttonLastPressed);
enableButton(buttonPressed);
buttonLastPressed = buttonPressed.getIndex()
}
}
Saves you from looping through each and every button to disable it.
Define id of button 1 to 100
When press button occurs save it's id in some member variable like previous_pressed
Before updating a previous_pressed value find and unpress previous pressed button like this
Button previous_pressed_button = (Button) findViewById(previous_pressed);
Now you have the previous pressed button, So upress it or whatever.

Button not clicking in Portrait Mode

I have a button to which I attach an onClickListener via code. I have to to this through code because it's in a fragment.
The listener works fine when in landscape mode, but when it's in portrait it doesn't. There's no "click" sound even.
In my xml file, I set the initial visibility of the button to invisible and then make it visible later when the user clicks a radio button in the same Viewgroup as the button. The onclicklisteners of the radiobuttons are working just fine in both portrait and landscape mode.
Now if I remove the "android:visibility="invisible" code in xml, the onclickstener works fine in portrait mode! But of course I need it invisible till the user clicks a radiobutton otherwise the UI doesn't make sense. Very weird indeed.
Here's my code:
private void setOnClickForSaveButton(View v) {
Button changeFundsSave = (Button) v.findViewById(R.id.change_funds_save);
changeFundsSave.setOnClickListener(saveListener);
}
Button.OnClickListener saveListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
//Get the rootview
View rootView = v.getRootView();
EditText changeFundsEdit = (EditText) rootView.findViewById(R.id.change_funds_edit);
if(changeFundsEdit.getText().toString().equals("")) {
new AlertDialog.Builder(getActivity())
.setTitle( "" )
.setMessage( "Enter the number of units" )
.setPositiveButton( "Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
return;
}
}
};
private void setOnClicksForRadioButtons(View v) {
RadioButton rb1 = (RadioButton)v.findViewById(R.id.add_units);
RadioButton rb2 = (RadioButton)v.findViewById(R.id.remove_units);
RadioButton rb3 = (RadioButton)v.findViewById(R.id.set_units);
rb1.setOnClickListener(addRemoveSetButtonListener);
rb2.setOnClickListener(addRemoveSetButtonListener);
rb3.setOnClickListener(addRemoveSetButtonListener);
}
OnClickListener addRemoveSetButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Since we only have the radiobutton view, we need to get the parent
View rootView = v.getRootView();
//Make the controls visible
TextView changeFundsText = (TextView) rootView.findViewById(R.id.change_funds_text);
EditText changeFundsEdit = (EditText) rootView.findViewById(R.id.change_funds_edit);
Button changeFundsSave = (Button) rootView.findViewById(R.id.change_funds_save);
changeFundsText.setVisibility(View.VISIBLE);
changeFundsEdit.setVisibility(View.VISIBLE);
changeFundsSave.setVisibility(View.VISIBLE);
}
};
}
Solved the problem! In portrait mode, like everyone else I load one fragment in a separate activity. Out of habit I was calling setContentView(something) before loading the fragment! So ultimately the two layouts were overlapping each other and the visible and invisible buttons were overlapping each other and things must have gotten messed up. Damn, I'm not sure if I like the concept of fragments at all. My first time using them. But maybe I just need to learn how to wire them up properly before I get used to them :) Thank you so much for your help
my guess is that
1) do you findViewById again for the view you passed in setOnClickForSaveButton? since the old view will be destroyed and a view will be created when you change screen orientation
2) do you have multiple ids for R.id.change_funds_save
3) add a log at the first line of onclick(v) to see if it is called but goto another branch you didnt expect.
Unless you are loading two separate xml layout files from layout-land and layout-port, there shouldn't be much difference between landscape mode and portrait mode. That being said, I'm going to take a wild guess and say that your app is probably not working correctly due to configuration changes. Let me know if this is actually true... i.e. does your app work at first, but stops working when you rotate the screen?
If this is true, you should look into how the Activity lifecycle is affecting your views and onClickListeners.

Android: How to propagate click event to LinearLayout childs and change their drawable

I would like to create a linear layout which would behave similarly to ImageButton.
<LinearLayout
android:id="#+id/container"
style="?WidgetHomeIconContainer">
<ImageView
android:id="#+id/icon"
style="?WidgetHomeIcon" />
<TextView
android:id="#+id/title"
style="?WidgetHomeLabel"
android:text="#string/title"
android:textAppearance="?attr/TextHomeLabel" />
</LinearLayout>
In styles of ImageView, TextView and LinearLayout, I set a selectors for all states.
Now:
when I click on ImageView (I tried it also with ImageButton) - it behaves correctly and the image is changed according the selector xml.
when I click on LinearLayout - the linear layout is clicked, but the the ImageView and TextView don't change it's drawable/appearance
So I would like to do the following. When I click on parent LinearLayout, I need to change all it's childs to pressed state.
I tried to add following code to LinearLayout onClickListener to propagate the click:
#Override
public void onClick(View v)
{
LinearLayout l = (LinearLayout) v;
for(int i = 0; i < l.getChildCount(); i++)
{
l.getChildAt(i).setClickable(true);
l.getChildAt(i).performClick();
}
}
But it still reamins the same. Thank you very much for any help.
Put
android:duplicateParentState="true"
in your ImageView and TextView..then the views get its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.
Not only make for every child:
android:duplicateParentState="true"
But also additionally:
android:clickable="false"
This will prevent unexpected behaviour (or solution simply not working) if clickable child views are used.
SO Source
After having the same problem some months later, I found this solution:
private void setOnClickListeners() {
super.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick(v);
}
});
for (int index = 0; index < super.getChildCount(); index++) {
View view = super.getChildAt(index);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onClick(v);
}
});
}
}
protected void onClick(View v) {
// something to do here...
}
In my case, no one of the other solutions works!
I finally had to use OnTouchListener as explained here, capturing the event when the user clicks in the parent view, and removing all childs OnClickListener.
So the idea is, delegate the click behavior to the parent, and notify the child that is really clicked, if you want to propagate the event. ¡¡That's what we are looking for!!
Then, we need to check which child has been clicked. You can find a reference here to know how it´s done. But the idea is basiclly getting the area of the child, and asking for who contains the clicked coordinates, to perform his action (or not).
At first, my child view failed to get click from parent. After investigating, what I need to do to make it work are:
remove click listener on child view
adding click listener on parent view
So, I don't need to add these on every children.
android:duplicateParentState="true"
android:clickable="false"
I only add duplicateParentState to one of my child view.
My child view is now listening to parent click event.

Layout in android

I have three buttons in one activity.when each of the button is clicked ,different layout should be shown with in the same activity.for example if first button is clicked,edit boxes and button should be shown.if second buttojn is clicked listview should be shown etc..
Define different layout files for each layout.
Then after each click event have the intent call this particular activity recalled.
Have setContentView() called conditionally ie determining the particular clickevent and vice versa.
This you can do if you want complete activity to be layuot in diffrent manner. Otherwise if you want some widgets to be displayed on button click then it is pretty easy to show them on click event.
You might wanna consider a "TabWidget" for this. It actually does what you need.
A sample tutorial here.
Why don't you just include the all the layout elements in your single layout, then use the setVisibility attribute to turn them on and off, depending on which button is pressed.
Something like this pseudo code:
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view1.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
view2.setVisibility(View.VISIBLE);
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view1.setVisibility(View.VISIBLE);
view2.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
}
});

How to disable an Android button?

I have created a layout that contains two buttons, Next and Previous. In between the buttons I'm generating some dynamic views. So when I first launch the application I want to disable the "Previous" button since there wont be any previous views. I also want to disable the "Next" button when there are not more views to display. Is there anyway to disable the buttons?
Did you try this?
myButton.setEnabled(false);
Update: Thanks to Gwen. Almost forgot that android:clickable can be set in your XML layout to determine whether a button can be clickable or not.
Yes it can be disabled in XML
just using:
<Button
android:enabled="false"
/>
You can't enable it or disable it in your XML (since your layout is set at runtime), but you can set if it's clickable at the launch of the activity with android:clickable.
You just write a single line of code in your activity
Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(false);
When you want to enable the same button just write
Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(true);
In Java, once you have the reference of the button:
Button button = (Button) findviewById(R.id.button);
To enable/disable the button, you can use either:
button.setEnabled(false);
button.setEnabled(true);
Or:
button.setClickable(false);
button.setClickable(true);
Since you want to disable the button from the beginning, you can use button.setEnabled(false); in the onCreate method.
Otherwise, from XML, you can directly use:
android:clickable = "false"
So:
<Button
android:id="#+id/button"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/button_text"
android:clickable = "false" />
In my case,
myButton.setEnabled(false);
myButton.setEnabled(true);
is working fine and it is enabling and disabling the button as it should. But once the button state becomes disabled, it never goes back to the enabled state again, although it's clickable. I tried invalidating and refreshing the drawable state, but no luck.
myButton.invalidate();
myButton.refreshDrawableState();
If you or anyone having a similar issue, what works for me is setting the background drawable again. Works on any API Level.
myButton.setEnabled(true);
myButton.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.myButtonDrawable));
In Kotlin, if you refer the Button View with id then, enable/disable button as like
layout.xml
<Button
android:id="#+id/btn_start"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="#string/start"
android:layout_alignParentBottom="true"/>
activity.kt
btn_start.isEnabled = true //to enable button
btn_start.isEnabled = false //to disable button
With Kotlin you can do,
// to disable clicks
myButton.isClickable = false
// to disable button
myButton.isEnabled = false
// to enable clicks
myButton.isClickable = true
// to enable button
myButton.isEnabled = true
WRONG WAY IN LISTENER TO USE VARIABLE INSTEAD OF PARAMETER!!!
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
RIGHT WAY:
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** check given view by assertion or cast as u wish */
if(v instance of Button) {
/** cast */
Button button = (Button) v;
/** we can perform some check up */
if(button.getId() == EXPECTED_ID) {
/** disable view */
button.setEnabled(false)
button.setClickable(false);
}
} else {
/** you can for example find desired view by root view */
Button bt = (Button) v.getRootView().findViewById(R.id.btId);
/*check for button */
if(bt!=null) {
/** disable button view */
...
} else {
/** according to #jeroen-bollen remark
* we made assumption that we expected a view
* of type button here in other any case
*/
throw new IllegalArgumentException("Wrong argument: " +
"View passed to method is not a Button type!");
}
}
}
});
EDIT:
In reply to #jeroen-bollen
View.OnClickListener
is Interface definition for a callback to be invoked when a view is clicked.
with method definition
void onClick(View v);
when the view is clicked the View class object makes callback to method onClick() sending as parameter itself, so null view parameter should not occur if it does it's an Assertion Error it could happen for example when View object class was destroyed in meanwhile (for example collected by GC) or method was tampered due to hack
little about instanceof & null
JLS / 15.20.2. Type Comparison Operator instanceof
At run time, the result of the instanceof operator is true
if the value of the RelationalExpression is not null
and the reference could be cast to the ReferenceType
without raising a ClassCastException.
Otherwise the result is false.
three words from the Author
IF U ASK WHY ?
MOSTLY TO AVOID NullPointerException
Little more code will save your time on later bug tracking in your code & reduces the occurrence of abnomalies.
consider following example:
View.OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)
If you need to disable button add this line of code.
Button button = findViewById(R.id.button)
button.setEnabled(false);
And enable button , just add this line
button.setEnabled(true);
Happy coding :D
first in xml make the button as android:clickable="false"
<Button
android:id="#+id/btn_send"
android:clickable="false"/>
then in your code, inside oncreate() method set the button property as
btn.setClickable(true);
then inside the button click change the code into
btn.setClickable(false);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnSend = (Button) findViewById(R.id.btn_send);
btnSend.setClickable(true);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnSend.setClickable(false);
}
});
}
You can disable a button from your xml but that won't be dynamic. Best way to disable button dynamically is.
myButton.setEnabled(false);
Just use setEnabled method in Java.
myButton.setEnabled(false);
And in Kotlin
myButton.enabled = false

Categories

Resources