Button to hide a TextView - android

I've been searching for a solution for this for a while but cannot seem to get one working. There are one or two on here about this subject but I can't seem to get them going. I'm also a novice in Android and while I've been on and off playing with it for a few years, I still understand next to nothing about what I'm writing.
Basically I've got a TextView and a button. Ideally I'd like to put some text in the TextView, press a button it's gone, press the button again and it's back.
I've narrowed it down to needing to understand what findViewById(R.id.button2) does but honestly I'm a bit lost.
I've added my button code but apologies that this is such a noob question
public void onClick(Button v){
TextView t1 = (TextView)findViewById(R.id.editText);
v.setVisibility(View.GONE);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView t1 = (TextView)findViewById(R.id.TextView);
v.setVisibility(View.GONE);
}
});
}

Your code has a couple of issues. I'm not going to give you the code because that won't really help you learn. Instead I'll explain things and let you try to figure it out or come back with more explicit questions.
You know that xml file you set using setContentView? Some of the tags in it had a property android:id="xxxx". That xxxx is the id of that view, its used so you can find that view in your code. The findViewById function walks through all the views on screen and finds a view with that id and returns it. That gives you a reference to the view so you can change it. For example, you can set its visibility, set its background color, or set an OnClickListener.
So to have a button toggle the visibility of another view, you need to be able to do the following things:
1)Find the view who's visibility you want to change
2)Figure out what its visibility currently is
3)Figure out what you want it to be (the opposite of what it currently is
4)Set that visibility
You need to write a function that does all that. Then you need to do this
1)Find the button you want to use to change the visibility
2)Tell it to call your function when its pressed.
Figure out how to do each of those steps individually, and you should be able to put it together. Good luck.

findViewById(R.id.button2) finds the view with the id button2.
You can check inside onClick whether t1 is visible or not (t1.setVisibility(View.GONE); not v.setVisibility(View.GONE);), and toggle between View.GONE and View.VISIBLE.
Remember that your findViewById() should have a real id. They are normally set on the activity_name.xml.
You are using a onClick inside a onClick. Personally I recommend setting the listener manually with setOnClickListener.
There's a lot of work for you, start with these tutorials. Keep trying and try to understand what you are doing.

Look like you need a toogle button feature, here is a piece of code.
Important: you must pay heed to #GabeSechan and #SkyDriver2500 answers.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//your other code
Button button = (Button) findViewById(R.id.button2);
final TextView t1 = (TextView) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
t1.setVisibility(t1.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
}
});
}

I'm not sure if the code will help you now. But just in case, here it is
final boolean[] isTvVisible = {false};
final TextView t1 = (TextView)findViewById(R.id.editText);
t1.setVisibility(View.GONE);
Button button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isTvVisible[0]) {
t1.setVisibility(View.GONE);
isTvVisible[0] = false;
} else {
t1.setVisibility(View.VISIBLE);
isTvVisible[0] = true;
}
}
});

Related

Android how to show hidden item only for one row on click

im trying to create a listView, that has an Button item on it.
I want to make this button clickable, so I did something like this code in Adapter, getView:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("_myButton_Log", "ShowOnClick");
}
});
And now im trying to change the visibility parameter for my textView:
TextView myDesc = row.findViewById(R.id.my_desc);
myDesc.setVisibility(convertView.GONE);
I want to show this textView in only one row, after click this button.
Now I make that, the button is clickable for each rows but as you can see it's show only the Log. Im a newbie in the ListViews and buttons on it and im trying to get knowledge how to make it work, but for now I cannot find any help...
So im begging here for some help! :)
Anyway if you want me to use the OnItemClickListener it's not possible because im using it for another way.
Ok I found out an response for my question.
Everyone with this problem - just need to make a simple action for a button in list view in your adapter like:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView myPrice = row.findViewById(R.id.price);
Button myButton = row.findViewById(R.id.button);
myPrice.setVisibility(convertView.VISIBLE);
myButton.setVisibility(convertView.GONE);
}
});

Android view isDirty inside onClick

I want to check if the text in some EditText is changed, after user clicks some Button. But View#isDirty seems not to return the correct state of the EditText if called inside onClick. For instance, I wrote something like this:
public class MainActivity extends Activity {
EditText editText;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.f);
editText = (EditText) findViewById(R.id.e);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
}
});
}
}
before i make any change to the editText, it outputs is clean, as expected. But the same is clean is printed even after I write something in editText.
When will isDirty be called? And is it the correct way to do this at all?
Update:
I also want to check if some Switch and Spinner values are changed. Is isDirty() the correct way to do this?
By the time you click your button edittext is no longer dirty - text is already updated and view redrawn. Maybe if you change your onclick handler you will understand better what is going on.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText = (EditText) findViewById(R.id.e);
System.out.println((editText.isDirty() ? "is dirty" : "is clean"));
}
});
isDirty will return true only as long as view has not been redrawn. This happens quite quickly and basically you do not have (and dont need) any control over this.
I think you need to use some other methods to achieve what you want.
I would suggest to use:
https://stackoverflow.com/a/9459848/5684335
The comment from Okas is a good explanation why.

Dynamically populate a button value android

I have seen lots of example to which one use a if condition or a case statement to programmatically change the conditions of elements...yadda yadda. I need to change the value of a button based on what the user clicks. Below is the code that I currently have.
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){CONTINUES TO OTHER FUNCTIONS }
I basically need to know what button was pressed. Then dynamically populate it into findViewById() function. i.e.
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
This way by the time it gets to the final Button part of the code it will have the value to which the user clicked on. Code works if I only want to have one button or a page mile deep in different configuration (not ideal).
All the examples I have seen so far are after the user clicks the button (which is what I want) but they name the buttons name statically like above code shows but very much static.
Hope that all makes sense.
UPDATE:
I think I may have confused the situation. Below is the remaining code. Hopefully this will provide context. The btnOpenPopup needs to remain the same as it's used in the call to execute the command for a new window to actually popup. Hopefully this will provide a bit more context for what I'm trying to achieve.
final Button finalBtnOpenPopup = btnOpenPopup;
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.meditationpopup, null);
//set the title of the popup
TextView titletext = (TextView) popupView.findViewById(R.id.chakratitle);
titletext.setText(activityName);
if (activityName.equals("Root"))
{
switch (arg0.getId())
{
case R.id.color:
//Rename the string so to get the value from the string xml
String stringName = activityName.toLowerCase().replaceAll(" ","")+"color";
TextView desctext = (TextView) popupView.findViewById(R.id.popupDesc);
desctext.setText(getString(getStringResource(getApplicationContext(),stringName)));
break;
case R.id.polarity:
//Rename the string so to get the value from the string xml
String polarityString = activityName.toLowerCase().replaceAll(" ","")+"polarity";
TextView polarityDesc = (TextView) popupView.findViewById(R.id.popupDesc);
//polarityDesc.setText(activityName);
polarityDesc.setText(getString(getStringResource(getApplicationContext(),polarityString)));
break;
}
}
I think
Button btnOpenPopup = (Button)findViewById(R.id.polarity);
btnOpenPopup = (Button) findViewById(R.id.color);
should be
Button btnOpenPopupFirst = (Button)findViewById(R.id.polarity);
Button btnOpenPopupSecond = (Button) findViewById(R.id.color);
you should declare different different button for diffrerent findviewbyid
also in my eclipse it is not accepting
btnOpenPopup.setOnClickListener(new Button.OnClickListener()
instead it works with
btnOpenPopup.setOnClickListener(new View.OnClickListener() {}
and you need to provide more clear view of what you want to perform
new thoughts,try doing this:
btnOpenPopupFirst.setOnClickListener(this);
btnOpenPopupSecond.setOnClickListener(this);
then option will come on both the above code lines
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (MainActivity)
choose this
let MainActivity implement OnClickListener
then this option will come
The type MainActivity must implement the inherited abstract method View.OnClickListener.onClick(View)
choose
add unimplemented method
now
#Override
public void onClick(View v)
will be created
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.polarity:
Toast.makeText(getApplicationContext(), "btnOpenPopupFirst(polarity) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
break;
case R.id.color:
Toast.makeText(getApplicationContext(), "btnOpenPopupSecond(color) is pressed", Toast.LENGTH_SHORT).show();
//other code to be performed regarding this button
default:
break;
}
}
And post your views after implementing this way.
int[] id={R.id.button1,R.id.button2};
Button b=(Button)findViewById(id[i]);
The onClick method in Button.OnClickListener has a View parameter... you can call getId() on that view to get the id of that button that was clicked on.
It doesn't make too much sense to me. If what you really want is this:
btnOpenPopup = (Button) findViewById(R.id.DYNAMTICVALUEOFBUTTONUSERHASPRESSED);
All you need to do is set your value in the onClick(View view) method of your OnClickListener
public void onClick(View view) {
btnOpenPopup = (Button)view;
}

How do I go from one page to another without using Intent?

I want to create an application based on quiz which consists of 14 questions.
Can anyone tell me how do I need to go from one question to another by clicking on next button.If I use an Intent then I am afraid that I will be creating 14 Activities :(
I don't think that is the programmatic procedure too.
You can stay in the same Activity and keep track of the question.
You might want to use a TextSwitcher to add a fade in/fade out animation when swapping the question's text.
You could have the button click just update the questions text to be the next question.
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
questionTextView.setText(questionTwo);
}
});
#Vivek you can use view flipper
this might help you
http://www.bogotobogo.com/Android/android9TabWidgetFlipper.html#SlidingDrawer
http://www.warriorpoint.com/blog/2009/05/29/android-switching-screens-by-dragging-over-the-touch-screen/
Change the text of your textviews where the questions are.
#Override
protected void onCreate(Bundle savedInstanceState) {
Button nextButton = (Button) findViewById(R.id.yourButtonId);
TextView questionTextView = (TextView) findViewById(R.id.yourTextViewId);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
questionTextView.setText("Your Next Question");
}
});
}
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity.
Has its own lifecycle;
Receives its own input events;
Can be added or removed while the activity is running;
Believe me that is the best method. I have been introduced to fragments having an application with quotes. The list of the quotes in left and the quotes that were changing on left when an author have been selected.
I'm using android.widget.ViewFlipper that contains views where one view contains TextView (question) and "input control" for answer (selectboxes, date/time widget, radiogroup, etc).

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