Very simple example about a button in Android? - android

I want a very simple button with some explanation/vizual-thing, perhaps onCreate/onLauncher to do what makes you smile! I have tried buttons here but errs here, probably easiest if someone could direct me to a ready working example about a button in Android. History shows problems with R and XML -files, probably easiest if someone could state it clearly how to do it: a very simple button. Its directory tree etc?
Please, provide a simple example about a button in Android, nothing else.

Go into the xml for the buttons and set an onClick attribute of "runClient".
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="runClient"
android:text="=)" />
UPDATE:
You should see something like this in eclipse.
UPDATE 2:
This is an example android project file tree. Highlighted is where the layout.xml should be.

First, let's take a look at your test.java, it won't work as is. I hope you understand basic concepts of object-oriented programming and get rid of the static methods.
In Android there's a class called Activity which you need to extend. If you followed Lazy Ninja's answer, the Eclipse plugin might have already created that one for you (it may be called MainActivity.java). Simply put, an activity represents a view in your application. In your trivial example, most if not all, your code goes to that class.
In Android, you don't use public static void main(String[] args), but override the activity's onCreate method. In the AndroidManifest.xml you define your activities (at this point you only need one) as well as which is the one launched when your application starts, and whose onCreate is the starting point of the whole app (again see the structure created by the Eclipse).
In onCreate you should call setContentView with the layout you wish to use in that activity. The layout is given to the setContentView as an integer parameter from the generated R class, like R.layout.layout_file_name which maps to the XML file at res/layout/layout_file_name.xml.
The layout file is the one that contains the declaration of the desired layout. In your case, it might have a LinearLayout as the root element and two Buttons.

In your main activity use something like this:
//Part of onCreate
Button b1;
setContentView(whatever.it.is);
b1 = (Button)findViewById(R.id.buttonID);
b1.setOnClickListener(buttonAddOnClickListener);
//Outside of onCreate, on its own
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
//Switch statement so you don't have to use a lot of click listeners
switch (arg0.getId()) {
case R.id.b1:
doSomething();
case R.id.b2:
doSomethingElse();
}
}
};
In your XML when you implement the button make sure to add this:
android:id="#+id/anID"
Change anID to the id you want.
Also I prefer IntelliJ (http://www.jetbrains.com/idea/) for Android programming. Your XML should be in a folder titled 'res' then in a subdirectory 'layout'. If you don't see those folders your project might not be set up correctly.

On eclipse
Click File -> New -> Other, a dialog will pop up.
From the dialog, select Android -> Android application project and
hit next.
A New Android Project dialog will popup, fill Application, Project
and packages names Chose SDK version
Follow the wizard until you click Finish
There you will have your android project file. And you layout xml file will be the res -> layout folder.
I think you should read Android Training to get you start.

Answer step by step to your question :
Mostly, XML file store in the /res folder where you can define
the interface of Android UI. For example, if you have 2 activities in your app, you can create 2 xml files ( layout of an activity ) represent of that 2 activities.
In the /src directory is just for java file. XML file should be created in the /res/... directory.
Each view of XML file has an id. When you first create an android project. the main activity already set a content view of your first app using method of Activity Class.
setContentView(R.layout.main)
-layout - represent layout folder in the /res folder
-main - represent an XML file in the /res/layout folder.
You can find out more with android doc

The easiest way to make a button, or any other Android GUI is with REBOL 3:
REBOL []
load-gui
view [button "Click Me" on-action [request "" "Clicked!"]]
That's a fully functioning GUI program, with all the power of the core REBOL language available to do networking, list processing, text parsing, file managment, etc. That program, and any other for R3 will run on Android AND on desktop OSs, using the exact same code. Take a look at:
http://rebolforum.com/index.cgi?f=printtopic&permalink=Nick25-Aug-2013/10:08:38-7:00&archiveflag=new

It looks like with your updated information and code that you are not initializing the button properly.
There is no need for this line:
setContentView(myButton1);
What setContentView(); does is it sets the xml view.
Button myButton1 = (Button) findViewById(R.id.button1);
The above line is what is really good for you. You now can use:
myButton1.setOnClickListener(buttonListener);
Button.OnClickListener buttonListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
//Switch statement so you don't have to use a lot of click listeners
switch (arg0.getId()) {
case R.id.myButton1:
doSomething();
case R.id.b2:
doSomethingElse();
}
}
};
Also the code you have set up is not an Android setup. You are using
public static void main(String[] args)
Which you don't want in an Android project. Please watch some videos on how to setup this appropriately. This line:
Button myButton1 = (Button) findViewById(R.id.button1);
Has an error because 'R' is not something your IDE knows right now because the project is not set up correctly. Once you do so a lot of your problems will be fixed. You would be running it instead of through main(String[] args), on onCreate() etc... And again I highly recommend IntelliJ, it makes it really easy to setup an Android project, even more so than Eclipse.

Related

How to use the 'AppIntro' package in android?

I am looking for a way to create a First-Start Tutorial for an App, and I found the following package: AppIntro for that.
Probably a nice package, but I have no clue on how to use it. Some pieces of how to use it are given, but no full downloadable example project.
Is there an example app somewhere on how to use this AppIntro package, or do I have to experiment on my own for days in order to learn how to use it ...?
There is an example project given here, but upon compiling this project I see nothing that actually resembles what I was expecting. I was expecting what is shown the original page in the first images. Some pages you can 'slide', with some dots on the button showing on which tutorial page you are.
Actually, some working hints come from
the video tutorial given on the main page of the library
and using the class SampleSlide given somewhere in the example section.
However, at the end, the Intro never starts, as the SharedPreferences firstStart is always set to 'false'. Now I need to figure out a way to 'reset' the SharedPreferences...
Solution:
Do not follow the code exampled given on the main page
Follow the Video tutorial
Download the not-working example code
Find the code for SampleSlide somwehere in the example code
Insert a button in order to 'reset' the shared preferences
Use this code to 'reset' the shared preferences:
public void resetPrefs(View view) {
// Make a new preferences editor
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
getPrefs.edit().clear().commit();
// changes layout
}
When I have some time I will put the COMPLETE and FULLY WORKING code in here later ...
Here's how I implemented it:
Added the dependencies in root build.gradle and app-level build.gradle.
Added a java file named IntroActivity.java and inserted the necessary code.
Along with the above java file, I created respective XML layout
files and called them in the addSlide function.
I also added the BaseSlide.java (or SampleSlide.java) for
Fragments.
Finally, added the Manifest declaration.

Eclipse ADT not responding temporarily

I am coding on Eclipse-ADT , right now there are too many xlm files and classes in project. When i want to add some code related to the xml members eclipse stop not responding for about 4-5 minutes. I think the problem is on xml search or verification but i am not sure.
For example , to add button , i write Button button1=(Button)findViewById(R.id.button1)
while coding this , there is no problem before (R.id.button1) , but when i write R.id.button1 eclipse crashes.
I searched the related questions on stackoverflow but couldnt manage the find the problem.
P.S : My original project was somewhere else on computer , if i choose the workspace as original locaiton , my project becomes invisible , so i decided to create a new workspace and import my original project. This may cause a problem but any suggestion how to handle it ?
I think it crashes even if it's just not responding. Maybe you don't have any buttons in the current Activity named "button1".
In the XML file, open the code interface and change respective button_id tag to "button1".
In the .java file change the setContentView tro "main" and add the:
(Button) findViewById(R.id.button1);
in your "main".

Editing layout in Android

I have two questions :
I am developing part of an Android App , in the main activity I added two text fields and one button and I am trying to call them by id as shown below :
Send = (Button)findViewById(R.id.Send) // Giving error in Send
StudentName=(EditText)findViewById(R.id.edittext); // Giving error in edittext
and then I added OnClickListener to the button , as shown below :
Send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
job = new MyJob();
job.execute();
}
});
I added both Send (my button and the textfields) in the R.java but it is not accepting them because the modification was done manually . I added import android.R , but it did not solve the problem .
My second question :
I am trying to edit my layout (graphically) but I do not know how to show it in eclipse !!!
Please Help me and sorry if my questions are stupid .
import android.R
android.R are resources from the Android package. TYou need to import your.package.R
For editing a layout in Eclipse open up the XML for the view/layout you are making. Then at the bottom of the code just above the tabs that say declaration, problems, javadoc there should be a tab that says Graphical Layout this will show your layout graphically.
Importing stuff by Id is done how blackbelt has said
Firstly, delete the "Gen" (automatically generated files) package and then clean the project, the errors will go away.
Secondly, for layout design you can open the .xml files and switch to design tab for the GUI way to edit layouts. Hope that makes sense.

Android Graphical UI Builders - Connect event

Maybe this question has been ask already, but could not find any answer for almost 2hours of internet search.
There is a graphical UI designer wich is coming along with the last android SDK.
Looks pretty cool and well done.
Nevertheless I * cannot find how to attach an event to the control through the graphical editor.
Of course I can add it manually into the xml, but in that case, what's the purpose of having such tool without that function ?
I mean all the other SDK I had in other languages always include that function.
I've also not been able to find doc about how to use this tool. Quite sad...
Thanks
If you want to add a click event handler, select the button (widget) in the GUI that you want to listen for, and look for the property onClick. Enter the name of the method you want to call when the user clicks on that widget, like.. onMyButtonClick
Then add the method to your Activity
public void onMyButtonClick(View v) {
// I heard the button click
}
The GUI builder is getting there, and is not yet as easy to use as the one in XCode, but it's not hard when you get used to it.

eclipse error with android: id cannot be resolved or is not a field

I just started playing around with android development, and already with just an attempt at making a button, I have encountered a problem.
The error I'm given in the following code is right on "R.id.button1".
It says id cannot be resolved or is not a field.
Do I need to manually reference every single object I make in the layout xml file? I found that this did work, but it does seem to be a bit much for every button I want to make...
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
}
I've been wasting a lot of time (two weeks) because of the same problem until I discovered the problem wasn't mine but Eclipse's.
I guess there's a lot of people with the same problem.
Just try this: Save your project, close Eclipse and then open it again. So simple.
Do I need to manually reference every single object I make in the layout xml file
Yes, otherwise you won't be able to do anything with those views. It's not that bad actually. So, each time you create a view in your XML, and you want to reference it, put an ID:
<View
android:id="#+id/the_id"/>
And then, from your code you can reference it using the R class. You can type, in the example, R.id.the_id and then Ctrl+Shift+O to make Eclipse auto import the needed files.
You can speed up your productivity by using frameworks like Roboguice; I think it's for lazy people, though.
This answer is not applicable to this question (looking at code you have provided). Just adding it if someone else stumbles here and above mentioned answers do not help.
If cleaning (Project --> clean) doesn't helps or saving and restarting eclipse doesn't help either, check for the following incorrect import.
import android.R;
Which Eclipse sometimes add by mistake on auto-import (Ctrl+Shift+O).
Remove that line (import) and it's done :D
Following this EXCELLENT tutorial , I encountered the same problem. After reading Carmello's answer (Sept 17, 2011. 07:23) I simply clicked File->Save All, and voila, 'button0' was automagically defined, and even syntax highlighted.
If "R.id.button1" is not defined, then you'll get a compile error, just as you saw. If you don't define this in the layout, then it won't be defined.
You don't have to specify every object you create in the layout, but you do if you try to reference it from "R.*". You can manually create buttons and other objects that are not specified in the layout.
I ran through the same issues for time being. Plz, do not forget to define as follows:
<View
android:id="#+id/button1" />
if you are using the id in your .java class.
Button b =(Button) findViewById(R.id.button1);
Being said that, the id defined in xml file must match with the id in findViewById().
Go to the 'R.java' file under the 'gen' folder and check whether your 'button1' is present under the class 'id'.If not,then this could be the reason you got that error.When you use the statement " R.id. " make sure that the is present under the appropriate class,in this case under the 'id' class.
R.id is a generated object that assigns int numbers to resources. Try this go to your gen/mypackage/R.java and delete the file. As you can see it is re-generated. This file provides static references where as the context is more of the dynamic state of your app. If you have syntax errors that will prevent automatic re-generation of that R.java file so you will get lots or R. errors. As everyone else has said you can click save all icon or ctl+shift+s on windows. You can clean the project project/clean and that will clean up 95% of those exceptions. Yes eclipse is buggy that way but netbeans does not support android that well. this link may help
Good luck
Do these things,anyone of this will help you
Project -> Clean,
Right click -> Fix Project Properties
Restart Eclipse
make some fake modification in manifest and save
check your console for any error message
check your drawable folder, check the image names satisfy the rules

Categories

Resources