Hi i am trying to make a public function in order to change activities/changes in my android application.
In a external class (Utl.java) I have this code.
public class Utl extends Activity{
public void onBtnClicked(View v) {
Intent i;
Integer data=0;
switch(v.getId()){
case R.id.btnStart:
i=new Intent(getApplicationContext(), LevelChoose.class);
startActivity(i);
break;
case R.id.btnEasy:
i=new Intent(getApplicationContext(), PlayGame.class);
startActivity(i);
break;
case R.id.btnMedium:
i=new Intent(getApplicationContext(), PlayGame.class);
data=48;
i.putExtra("extra", data);
startActivity(i);
break;
case R.id.btnHard:
i=new Intent(getApplicationContext(), PlayGame.class);
data=96;
i.putExtra("extra", data);
startActivity(i);
break;
}
}
}
and in my xml's files i use the on click function of the buttons...
<Button
android:id="#+id/btnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="42dp"
android:minHeight="110dp"
android:text="Start Game"
android:onClick="cls2.onBtnClicked(this)" />
I get that the function can't be found...
I wish to dynamically change screens.... Thank you for your time!!
You can use the constructor where you can assign the current context. Try this example
public void sampleMethod(final Activity cont)
{
Intent intent = new Intent(cont, XYZ.class);
cont.finish();
cont.startActivity(intent);
}
also move this method to a util class and call it from activity and pass the activity reference as follows
class ActivityB extends Activity
{
Util.sampleMethod(this);
}
You have multiple issues in your code. I'll try to list them here:
You cannot pass a method of any class to android:onClick.
You'll have to set the onClickListener for your Buttons in code, using
yourButton.setOnClickListener(new Utl());
Don't make Utl a subclass of Activity. Use Activity only for different "screens". You'll want to use Object instead here. If you need a Context in Utl, add a class member and take a Context in the constructor, like this:
private Context mContext;
public Utls (Context c){
mContext = c;
}
Now, instantiate Utls like this:
yourButton.setOnClickListener(new Utl(this));
Just change this line
android:onClick="cls2.onBtnClicked(this)"
to
android:onClick="onBtnClicked"
View will be passed to function automatically.
Happy coding..:)
Related
What I am trying to achieve here is create a java class that will allow me to call the method inside the class for an activity transitioning.
For instance, I have 3 activities: Main.xml, A activity.xml, B activity.xml. I want to create a class that I can call from main's java class to transition to A and then from A to B.
I thought maybe it would be somewhere along that lines of:
[Transitioning activity class]
//Behind the scenes for activity transitioning, I don't know how to write this part or if calling it is correct
Intent intent = new Intent(?, ?); startActivity(intent); overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
[Main]
//calling intent from activity transitioning class
intent(this, A_activity.class);
[A Activity]
//calling intent from activity transitioning class
intent(this, B_activity.class);
Also I want to apologize, this is indeed my first rodeo, I am self-taught and have no professional experience in programming or developing. Thank you in advance!
So far what I am currently doing is creating the transitions in each class:
[A activity]
public void onClick(View v){
switch(v.getId()){
case R.id.commBtn:
inqList.clear();
inqAdd.addItem("Commercial");
System.out.println(inqList);
onTransition();
break;
case R.id.resBtn:
inqList.clear();
inqAdd.addItem("Residential");
System.out.println(inqList);
onTransition();
break;
default:
break;
}
}
//Method for transition after clicked
public void onTransition(){
Intent intent = new Intent(this, b_scene.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
**[Edit]**
///I did this and it works? not sure if its best practice but it worked.
[Transition Class]
public class Transition {
public static void onTrans(Activity activity, Class name) {
Intent intent = new Intent(activity, name);
activity.startActivity(intent);
activity.overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
}
[A Activity]
///Just put this in A activity
public void onClick(View v){
...
onTrans(this, B_Activity.class)
}
Sure you can but since that transition class is not an Activity instance (which has the startActivity() method), you need to pass the Activity instance as well, e.g.:
public static void navigateTo(Activity source, Activity destination) {
Intent intent = new Intent(activity, destination.class);
source.startActivity(intent);
source.overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
Another common option is to use an abstract BaseActivity that has this method onTransition() and extend your activities from this one (you can also use composition instead of inheritance for a better practice).
I'm trying to make an app that asks the user maths questions. I have a number of buttons, such as multiplication, addition etc. I want my code to have a series of if/else statements that tells it what operator to use based on which button was clicked in the previous activity.
What do I use to access this information?
You can always pass argument to You activity using Extra and perform some actions based on its value.
int extraValue = 5;
Intent i = new Intent();
i.putExtra("EXTRA_NAME", extraValue);
startActivity(i);
Then You can obtain this extra by its name in your target activity.
extraValue = getIntent().getIntExtra("EXTRA_NAME", -1); // here -1 is default value.
Just put the button id in the intent. Like this;
Intent i=new Intent(context,MyActivity.class);
i.putExtra("button_id", buttonID);
context.startActivity(i);`
Then in your Activity;
Intent I =get intent();
Int buttonID = intent.getIntExtra("button_id");
A new activity is always started by an intent. If we want to start an activity with some information, we can put the same in that intent which is used to start it. This intent can be caught by getIntent() method in started activity.
Example:
In your first activity:
intent = new Intent(MainActivity.this,SecondActivity.class);
switch(radioGroup.getCheckedRadioButtonId()){
case R.id.add:
intent.putExtra("operator","add");
startActivity(intent);
break;
case R.id.subtract:
intent.putExtra("operator","subtract");
startActivity(intent);
break;
case R.id.multiply:
intent.putExtra("operator","multiply");
startActivity(intent);
break;
case R.id.divide:
intent.putExtra("operator","divide");
startActivity(intent);
break;
}
And in your second activity:
public class SecondActivity extends AppCompatActivity {
Intent intent;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
intent = getIntent();
String operation = intent.getStringExtra("operator");
switch(operation){
case "add":
//your code
break;
case "subtract":
//your code
break;
case "multiply":
//your code
break;
case "divide":
//your code
break;
}
}
}
I'm new to programming so I have a really easy question. Since I do not really know the terms I couldn't find any topic on my problem, so excuse me if this question has been asked before.
My problem is as follows: I'm running an app, created with Eclipse, on an Android machine. On the first screen I have just a list of buttons:
layout_main:
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="alpha" />
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="beta" />
If I press a button then the corresponding activity will start. I programmed the main activity as follow in order to do that:
main activity:
public void alpha(View view) {
Intent intent = new Intent(this, AlphaActivity.class);
startActivity(intent); }
public void beta(View view) {
Intent intent = new Intent(this, BetaActivity.class);
startActivity(intent); }
Since I have many buttons, I will have as many times the operation public void as seen above. Isn't there any way to program it more efficient? For example: Start new activity, if alpha was selected then start activity alpha, if beta was selected start activity beta, else do nothing.
You could apply the same listener to each button, not really sure if it's more efficient or even better style, but this will probably work. Something like:
public void buttonListen(View view)
{
Class clas;
int id = view.getId();
switch(id)
{
case R.id.alpha:
clas = AlphaActivity.class;
break;
case R.id.alpha:
clas = BetaActivity.class;
break;
...
case R.id.zeta:
clas = ZetaActivity.class;
break;
}
startActivity(new Intent(this, clas));
}
and assign the corresponding id in the XML as the next answer states.
you can give every button an id like this :
<Button
android:id="#+id/alpha"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
/>
<Button
android:id="#+id/beta"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
/>
then in the main activity you can findviewbyid() to find the two buttons and give buttons onclicklistener,then you implements the onclicklistener like this :
public void onClick(View v) {
Intent i = new Intent();
switch(v.getid()){
case: R.id.alpha:
i.setClass(context,AlphaActivity.class);
break;
case: R.id.beta:
i.setClass(context,BetaActivity.class);
break;
}
startActivity(i);
}
hope that helps.
There are many different ways to achieve this and make it simpler. Not a single method will be "the best". What you are doing is probably down the list of "what I would not do".
Don't assign things in XML, it's harder to work with, cannot be really changed at running time and make it less portable when you have to maintain a lot of different layouts. Instead…
This is just ONE way to do it:
Instead of defining the onClick method in the XML, do it programatically.
Add an android id to your Views:
<Button
android:id="#+id/alpha_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/alpha" />
(the same for all the other buttons)
Note: don't use fill_parent, use match_parent (the former is deprecated and both do the same).
The in your Activity onCreate() method, right before you setContentView(R.layout.your_above_layout_with_the_buttons);
You can obtain a reference to each button:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_above_layout_with_the_buttons);
final TextView alphaButton = (TextView) findViewById(R.id.alpha_button);
//etc for the rest
// now add click listeners:
alphaButton.setOnClickListener(this);// more on this later
betaButton.setOnClickListener(this);
// etc.
}
Now your activity should be:
public class YourActivity extends Activity implements View.OnClickListener {
and somewhere in your activity you have to implement:
#Override
public void onClick(final View view) {
// which button was clicked? Different ways to tell… a simple one:
Intent intent;
switch (v.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
//etc.
}
if (intent != null) {
startActivity(intent);
}
}
There are many ways you could accomplish your goal.
Note: the best solution would be to add android:id to your layout file, but if for some reason you can't do that, you could use the button text.
A very simple (although not great) way to do it without changing your layout file much would be to look at the text on the button, if all buttons have unique text, and perform the action based on that.
public void onButtonClick(View view)
{
//Cast the click View into a Button
Button selectedButton = (Button) view;
Intent intent = new Intent();
String buttonText = selectedButton.getText().toString();
if(buttonText.equals("beta"))
{
intent = new Intent(this, BetaActivity.class);
}
else if(buttonText.equals("alpha"))
{
intent = new Intent(this AlphaActivity.class);
}
startActivity(intent);
}
Make sure to set the onClick for each button in the layout file to call this method
android:onClick="onButtonClick"
For your specific situation, you could could change the way you handle the calls from your buttons, for example, you could give the buttons IDs and check the IDs of the buttons in a single method.
<Button
android:id="#+id/alpha_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/alpha"
android:onClick="onButtonClick" />
<Button
android:id="#+id/beta_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="#string/beta"
android:onClick="onButtonClick" />
public void onButtonClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.alpha_button:
intent = new Intent(this, AlphaActivity.class);
break;
case R.id.beta_button:
intent = new Intent(this, BetaActivity.class);
break;
default:
return;
}
startActivity(intent);
}
However, I would suggest that your current code is clear and concise so just leave it as it is. There are many ways to solve a problem, especially when it comes to designing software.
In general though, programming languages try to balance making code (and more importantly it's function or purpose) easy to read/understand while trying to keep the syntax as concise as possible. In time you will learn about the advantages and disadvantages of each language and it's syntax, some will be better at solving certain types of problem while being too verbose for solving others. For now just learn how Java works and try to understand why they have implemented each keyword and syntax element.
I am making a game in android. I want to make a main menu screen that has two buttons, one to start the game and one to display the how to screen.
I have classes for both, but when I launch my name and test the buttons, the application crashes. Could someone please tell me what is wrong with my code?
public void launch()
{
Intent i = new Intent();
i.setClassName("com.testing.blockinvasion", "com.testing.blockinvasion.game");
startActivity(i);
}
public void howto()
{
Intent i = new Intent();
i.setClassName("com.testing.blockinvasion", "com.testing.blockinvasion.howto");
startActivity(i);
}
}
My buttons are defined in my main.xml:
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/Start"
android:onClick="launch" />
EDIT: I ended up just deleting the project and starting another one and everything seems to work fine now.
You need to correct your method signatures. So do it in this way:
public void launch(View v)
and
public void howto(View v)
Try it this way:
private OnClickListener button1Listener = new OnClickListener() {
public void onClick(View v)
{
Intent howto = new Intent(getApplicationContext(), .class);
startActivity(howto);
}
};
Assigning a different OnClickListener object to every button --> button1.setOnClickListener(button1Listener)
Anyway, are all the Activities defined in the AndroidManifest.xml?
How do i call on a seperate activity within a method:
For example:
private void startApp() {
Patient_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want this Button to go to an Detailed_ModeActivity
// This is how i Am doing it right now, but it comes out with an
// error
Intent b = new Intent(this, Detailed_ModeActivity.class);
startActivity(b);
}
});
}
Any Help would be appreciated.
The Button was declared in the onCreate method
Like this:
Intent b = new Intent(v.getContext(), Detailed_ModeActivity.class);
startActivity(b);
The this refers to an View.OnClickListener object which doesn't have startActivity() method and cannot be passed to an Intent. You need to call startActivity() on a Context (e.g. an Activity). Let's say your code is in the MainActivity class. Like this:
Intent b = new Intent(MainActivity.this, Detailed_ModeActivity.class);
MainActivity.this.startActivity(b);
First up, make sure Detailed_ModeActivity extends Activity.
Secondly you need to add the activity class to the manifest.xml file if you haven't already.