Buttons using onClickListener - android

am new to android
I have seen many examples on creating buttons, but i just can't get what does each line mean :(
take the following piece of code as an ex.
connect = (Button) findViewById(R.id.button_connect)
connect.setOnClickListener(connectListener)
private OnClickListener connectListener = new OnClickListener() {
public void onClick(View v) {
Log.i("CONNECT PRESSED", "press")
// ....
// ....
// ....
};
what i know is that the first line Defines a button, but wht is findViewbyId?
i know the second line
but then when defining the listener, what's the log.i?
nd r "connect pressed" and "press" just labels for the button? f so why there r two for a single button...

You should have an additional Button connect; before those lines.
connect = (Button) findViewById(R.id.button_connect) // findViewById() in layman term it means, finding view by id. Which also means finding the view(button/textview/edittext) by ID(value you stated in your main.xml for the view. e.e. android:id=#+id/"")
connect.setOnClickListener(connectListener) //listens to a click when clicked
private OnClickListener connectListener = new OnClickListener() { //if button of android:id="button_connect" is clicked, Do this method.
public void onClick(View v) {
Log.i("CONNECT PRESSED", "press") //prints message in your logcat
// ....
// ....
// ....
};
If you still don't understand what does findViewById(), just think of it this way. View is man. Id is name. So in the end you are finding the man by name("Whatever this is")

In Android you normally define the layout of an Activity in an XML file. Each View element in a layout that you want to interact with in code needs an id. In you example the layout XML file needs to have a button with the id button_connect.
In the onCreate() method of an Activity you normally call setContentView() and pass it the layout you want to use in this Activity. E.g. setContentView(R.layout.my_layout); where your layout file's name is my_layout.xml.
The setContentView() method builds up the defined layout as objects and with findViewById(R.id.button_connect) you get a reference to a Button object from this layout whose id is button_connect.
Log.i() is simply logs the message "press" under the tag "CONNECT PRESSED" in the log cat.

It seem to be you didn't read basic things about android app development. Android Developers website providing information to learn android app development with good examples and tutorials. You are asking very basic things by just copying the code from tutorials.
Actually its not the right place for this kind of questions. First do practice by reading tutorials around the web.
Coming to your doubts regarding code you posted here, those are very basic things.
findViewById() finds a View by field Id, which is declared in XML layout file as below
Log.i() is LogCat info message displayed in your logcat window when debugging is enabled in your app.

in your example you probably have defined an xml layout file as the style of your activity with setContentView(R.layout.myXMLLayout);
If not, findViewById(R.id.button_connect) will fail.
R.id.button_connect refers to an id created in your xml layout.
There has to be a line android:id="#+id/button_connect" in a < Button > tag.
findViewById finds this Button (which is more genereally a view, which is why you have to cast it to a Button with the (Button) before findViewById(...) ). You then refer to exactly the button you've put in your xml.
Log.i("CONNECT PRESSED","press"); isn't necessary at all. It's just logging the press of the button and displays it in the log cat. It can be removed without any further impact. This is for debugging only and should be removed for any final (public) versions of your code.

Related

Listview Custom Adapter with Button Tags

I have been experiencing a problem with my custom adapter and have located the problem solution. However I do not know how to go about it. I have researched and seen a few examples of a listview custom adapter at which buttons are given tags like viewHolder.button.setTag(Tag) and I understand what the tag does but I am unsure as to how to use it. My questions are: When I set the tag on a button, how does the application differentiate my buttons from another if all the tags are set the same? Also, say I have an onClick method in my custom adapter, how do I use the tag that I set to the button to identify the button that was clicked? I've kind of seen similar adapters on the internet but not exactly , a link to an example would be greatly appreciated also.
I am unsure as to how to use it
tag is a mechanism to make your views remember something, that could be an object an integer a string or anything you like.
My questions are: When I set the tag on a button, how does the
application differentiate my buttons from another if all the tags are
set the same?
i do not understand this question but i think if you notice that your button has a memory and it calls tag you can use it in a better way. if all of your buttons memory(tags) are the same so you can not use tags to distinguish the buttons you must use ids.
say I have an onClick method in my custom adapter, how do I use the
tag that I set to the button to identify the button that was clicked?
you must set different tags for your buttons or grouped them logically and set different tags for each group then in your onClick method use the tags to identify your buttons group:
OnClickListener myButtonListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
Object obj = arg0.getTag();
if(obj instanceOf groupOneTagObject){
// do action for group 1
}else if(obj instanceOf groupTwoTagObject){
// do action for group 2
}
}
});

Displaying an array of objects, one at a time through a single dialog... instead of several dialogs

In my application I have a list of questions stored in an ArrayList, and I want to display a dialog that shows one question, and then continues to the next one after the question is answered. The way that I'm currently doing it (iterating through a loop) hasn't been working because it just layers all of the dialogs on top of one another all at once which causes a host of other issues. What I'm looking for is a way to still iterate through the questions, but just change the layout of the dialog each time until it has finished each question in the list. Can anyone give me a good pointer for how to get this going?
You can make a function that takes title and message as parameters and shows a dialog.
showDialog(String title, String message){ // Show dialog code here}
Within that dialog's answer button's listener call another function (showQuestion(currentQuestion)) that iterates the arrayList till it is over
int currentQuestion=0;
ArrayList<QuestionObject> questionList;
showQuestion(int i){
if(i<questionList.size()){
showDialog(questionList.get(i).getTitle,questionList.get(i).getMessage);
currentQuestion++;
}else{
//quiz is over
}
}
I assume you mean that you just want to change 1 single layout(created within XML i.e main.xml). In order to do this, make sure that the class your working on is pointing to that layout. From there (assuming your using an Event listener for when the user submits an answer) you can change do as you want by the following:
TextView txt = (TextView) findViewById(R.id.textView); // references the txt XML element
and in your Event listener, if the answer is correct then change(Have i be a global variable thats initially set to 0).
if(i<arrayList.size()){
txt.setText(arrayList.get(++i));
}else{
txt.setText("You Finished");
}
From there, in the else statement, you can change arrayLists and reset i to 0;
If you are trying to use the positive, neutral, and negative buttons; then you may have problems with multiple dialogs. Try defining a customized layout with your own TextViews, ListViews, and Buttons. You can implement listeners and everything else like a regular layout. Then just pass your customized layout to the dialog through AlertDialog.Builder.setView().
PS If you include code examples of what you are currently doing we can provided answers that are less vague.

android setBackgroundColor in runtime and other general confusion help?

i have a row of buttins created like this
i want to change the background colour at runtime in code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout track1 = (LinearLayout)findViewById(R.id.my_toggle_container);
for (int i = 0; i<32; i++) {
ToggleButton tgl = new ToggleButton(this);
tgl.setId(i);
...
track1.addView(tgl);
this names the id of the togglebuttons 1, 2, 3... (i presume?)
i have an int variable called 'xBtn' that changes 1, 2,..
this is how i get a reference to the button using xBtn
String buttonID = ""+xBtn;
int resID = getResources().getIdentifier(buttonID, "id", "com.thing");
//find the button
ToggleButton tb = (ToggleButton) findViewById(resID);
//change its colour
tb.setBackgroundColor(Color.BLUE);
it crashes on the setBackgroundColor line.
it may be obvious to someone whats wrong and thats what im hoping
any help would be totaly ace ta
thanks
main.xml
<LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:id="#+id/my_toggle_container" android:orientation="vertical">
The id of your togglebuttons is gonna be a number from 1 to 32... However, trying to find the toggle button by id will return null because simply instantiating a new toggle button and giving an id wont help you. findViewById looks in the parent view for a child view with the specified id. If you havent added that toggle button with that id to the view, then findViewById will return null. I am 99.99% sure even without looking at the log, that it crashes because you are calling setBackgroundColor on a null object.
In other words, the id that you set a view to is only relevant once the view is actually added to a parent view. In your case you are probably trying to add these toggle buttons to your main content view, in which case you need grab hold of that view that you used for setContentView and call addView on that view and pass in each new toggle button. Note that this will probably not look right unless you also specify layoutparams for the togglebuttons.
EDIT
If thats your entire main.xml, then you've got other issues. Post the full xml file. In any event, you still are going to have to do what I've said, which is to grab hold of the view or a child view of that view and then add the toggle buttons to it via addView (after giving the togglebuttons their proper ids). Once the button has been added, then you can find it. Note though that if you're gonna add the toggle buttons to a child view of your main view, then you'll likely have to grab hold of that child view and call findViewById on THAT.
For example, you can do a nested call like this. findViewById(1) <--- gets you the LinearLayout or whatever inside of your main content view, then once you have that you can call addView on it. So LinearLayout ll = (LinearLayout)findViewById(someNumber); ll.addView(tb);
Try to use the method setTag() , and then you can get all your ToggleButton by using : findViewByTag();
Perhaps tb is null? Could you check that out?
To expand on what LuxuryMode said... What gets an ID INTO your java is inflating it via setContentView and setting it as content. That's why it's ok to have overlapping (duplicate) IDs in different layouts. You can have #+id/submit_button in layout1.xml and in layout2.xml and the Activity will get you the object via findViewById(R.id.submit_button) based on which one you have loaded into setContentView() at any given moment.
So, we're all guessing that you're probably not setting the content view and hoping that the code will find your object in your non inflated XML, which it won't. Which would lead (as everyone has guessed) to you now dealing with a null object, which you obviously can't set a background color on.
I know it gets confusing cause you have the XML RIGHT THERE!!! But the reality is that the xml isn't "alive". It's just stuff for you to look at until you have tasked the Application with inflating it and converting all of it into Android objects of some kind. A lot of the time this is done mostly transparently to you, so, it's easy to forget that none of these things really exist.
It's very likely that tb is null, because findViewById() didn't go as you expected.
You can verify this by surrounding the erroneous line with try.. catch block:
try {
tb.setBackgroundColor(Color.BLUE);
} catch (Exception e){
}
and watch for the message of e. It's likely to be null pointer exception.
In fact, I think you should not use getResources().getIdentifier(buttonID, "id", "com.thing") in the first place. It seems to me that all these resources are continuously numbered in R file, thus you should simply get the first id (as an integer), and then increment on that.
That is, you should do things like:
// The following code is not tested; I just wrote it here on SO.
for (int resID = R.id.button1; resID <= 32; resID++) {
ToggleButton tb = (ToggleButton) findViewById(resID);
tb.setBackgroundColor(Color.BLUE);
}
this should make all 32 buttons blue.

How do i reference the objects created in the XML from the main .java program?

I am creating an android app using Eclipse. This is my first program using either eclipse or writing for android. I have created several objects in my XML (4buttons and a text-View). The program is supposed to display a random result in the text-View when one of the buttons are pressed. There is no problems with the code to determine the random result, but I cannot find how to reference the objects so as to edit the text-View or connect the buttons to the functions I have made. How do i reference the objects created in the XML from the main .java program?
For example:
R.layout.main // layout with "main" id
R.string.hello // string with "hello" id
R.id.button // button with "button" id
If you want to get a view, a button for example:
Button launch = (Button) findViewById(R.id.button_id);

"Force Close" Error on declaring TextView and ToggleButton

Well basicly I have a textview and when the application is created it sets a string as the textviews text not hard, but I get a force close error when I run the app on my phone.
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
Then I have a error on a togglebutton also
ToggleButton silent=(ToggleButton)findViewById(R.id.silentbutton);
silent.setChecked(false);
And I have errors for all my other buttons/textviews can anyone help, please?!
EDIT:
I cant post pics because I am a new member, :(
Link to imgshack http://imageshack.us/photo/my-images/849/unledggp.png/
If code for the whole textview snippet.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_UNMOUNTED)) {
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
}
OnCreate Function
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkSD();
checkRing();
checkWifi();
checkBt();
}
Look for all instances of sd_textview and make sure the one that you're trying to reference is a TextView. If you want more clarity you can debug your code and see what object is actually being returned by not casting into a TextView:
View sdcard = findViewById(R.id.sd_textview); //debug this
//you can also log the View object to see the type
Log.d("Test", "" + sdcard);
Looking at your error log (assuming its the right error log) you have a ClassCastException in the checkWifi method. Edit your question and include ALL of the onCreate method and all of the checkWifi method, but I expect you are using the same id for multiple views.
Two things I can think of (although seeing more code would help).
Make sure you have called setContentView(R.layout.main) (or whatever your layout file is called). Do this BEFORE any attempt to use findViewById(...).
Secondly sdcard.setText(R.string.not_mounted); in this statement R.string.not_mounted is a resource ID (int) and not a string. You would need to use...
sdcard.setText(getString(R.string.not_mounted));

Categories

Resources