Pretty new to android world, I am having an issue playing audio when clicking a button. The interesting/weird aspect of it is that same code works on my mainactivity but not on secondactivity that I have set up. I am using the same exact code that works on mainactivity. I used that code on mainactivity just to test it, keep in mind no media player has been declared or defined in mainactivity. I did that just to test to see if code works.
Here is my xml:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15sp"
android:layout_marginBottom="15sp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="press button to play audio"
android:textSize="40sp"
android:textColor="#ffff"
android:fontFamily="cursive"
android:textStyle="bold"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="10sp"
android:layout_gravity="center"
>
<Button
android:id="#+id/AudioButton"
android:layout_width="wrap_content"
android:layout_height="50sp"
android:text="play"
android:textSize="22sp"
android:textColor="#ffff"
android:layout_marginRight="10dp"
/>
</LinearLayout>
Here is JAVA:
package nameiscleared;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button start = (Button) findViewById(R.id.AudioButton);
start.setOnClickListener(new View.OnClickListener() {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname);
#Override
public void onClick(View view) {
mp.start();
}
});
}
}
It just my assumption, I think you are not releasing the MediaPlayer when you use it in MainActivity. That is why it is not working on secondActivity. Another mistake is, MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname); need to be in onClick, not in View.OnClickListener() bracket. You need to keep in mind that after you used MediaPlayer, you need to release it when it is no longer being used.
A MediaPlayer can consume valuable system resources. Therefore, you should always take extra precautions to make sure you are not hanging on to a MediaPlayer instance longer than necessary. When you are done with it, you should always call release() to make sure any system resources allocated to it are properly released. For example, if you are using a MediaPlayer and your activity receives a call to onStop(), you must release the MediaPlayer, because it makes little sense to hold on to it while your activity is not interacting with the user (unless you are playing media in the background, which is discussed in the next section). When your activity is resumed or restarted, of course, you need to create a new MediaPlayer and prepare it again before resuming playback - Android Developers documentation.
The correct implementation supposed to be like this;
MainActivity
public class MainActivity extends AppCompatActivity{
private Button playBtn, startActivityBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(MainActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
startActivityBtn = (Button)findViewById(R.id.startActivity);
startActivityBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
SecondActivity
public class SecondActivity extends AppCompatActivity {
private Button playBtn;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_econd);
playBtn = (Button)findViewById(R.id.playBtn);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer = MediaPlayer.create(SecondActivity.this, Settings.System.DEFAULT_RINGTONE_URI);
mediaPlayer.start();
}
});
}
#Override
protected void onStop() {
super.onStop();
if(null != mediaPlayer){
if(mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
}
I am not including the layout because both of the layout are very simple. MainActivity has two button, to play and to start another activity. SecondActivity has only play button.
Related
I have implemented the settings screen of my app using PreferenceFragment.
When the up button in the toolbar of the settings screen is clicked my app returns to the MainActivity screen but the data that was previously entered into the EditTexts (before going to the settings screen) is lost and the EditTexts are all blank.
I tried implementing onSaveInstanceState and onRestoreInstanceState but it is not working because onRestoreInstanceState is not called when clicking the up button in the settings screen toolbar. The savedInstanceState is also null in onCreate.
Would really appreciate it if someone could point out how to go about restoring the data in the EditTexts please? :)
Here's the log for MainActivity:
Clicking on Settings from toolbar menu:
I/LOG: onPause
I/LOG: onSaveInstanceState saving
I/LOG: onStop
Clicking on back button in settings screen toolbar:
I/LOG: onDestroy
I/LOG: onCreate
I/LOG: savedInstanceState is null
I/LOG: onStart
I/LOG: onResume
MainAcitivy.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.util.Log;
//...
public class MainActivity extends AppCompatActivity {
Toolbar toolbarMain;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("LOG", "onCreate");
super.onCreate(savedInstanceState);
Log.i("LOG", "savedInstanceState is " + savedInstanceState);
if(savedInstanceState !=null) {
editText.setText(savedInstanceState.getString("ET_KEY"), TextView.BufferType.EDITABLE);
}
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.myEditText);
toolbarMain = (Toolbar) findViewById(R.id.toolbar);
toolbarMain.setTitle(R.string.app_name);
toolbarMain.inflateMenu(R.menu.menu_main);
toolbarMain.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
return true;
}
});
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("LOG", "onRestoreInstanceState");
super.onRestoreInstanceState(savedInstanceState);
editText.setText(savedInstanceState.getString("ET_KEY"), TextView.BufferType.EDITABLE);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i("LOG", "onSaveInstanceState saving");
outState.putString("ET_KEY", editText.getText().toString());
}
#Override
public void onPause() {
Log.i("LOG", "onPause");
super.onPause();
}
#Override
public void onStop() {
Log.i("LOG", "onStop");
super.onStop();
}
#Override
public void onDestroy() {
Log.i("LOG", "onDestroy");
super.onDestroy();
}
#Override
public void onStart() {
Log.i("LOG", "onStart");
super.onStart();
}
#Override
public void onResume() {
Log.i("LOG", "onResume");
super.onResume();
}
SettingsActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
SharedPreferences sharedPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences_layout);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(R.id.pref_content, new SettingsFragment())
.commit();
}
}
I found a solution after much searching. Hope the following helps anyone else out there.
Initially, I tried to override the behaviour of the up button. However I was getting a 'cannot resolve symbol' error on MenuItem when trying to override onOptionsItemSelected. Perhaps there is a way to do this but I couldn't figure it out. I gave up on this approach when I noticed this in the Android Developer Docs:
You do not need to catch the up action in the activity's onOptionsItemSelected() method. Instead, that method should call its superclass, as shown in Respond to Actions. The superclass method responds to the Up selection by navigating to the parent activity, as specified in the app manifest.
Solution
A solution that did work for me was to create a custom toolbar so that I could define the behaviour of the up button entirely. Thankfully this only required a few lines of code.
Step 1 - Create a new toolbar layout
res/layout/toolbar_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbarPreferences"
android:background="#color/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:elevation="4dp"
android:theme="#style/ToolbarTheme"
app:navigationIcon="?attr/homeAsUpIndicator"
app:titleTextColor="#color/white">
</android.support.v7.widget.Toolbar>
Note the line in the above:
app:navigationIcon="?attr/homeAsUpIndicator"
Step 2 - Refer to new toolbar in preferences layout file
In my case, in my preferences_layout.xml:
<include layout="#layout/toolbar_preferences" />
Step 3 - Java code
In SettingsActivity.java, I had to:
First, initiate the new toolbar:
Toolbar toolbarPref = (Toolbar) findViewById(R.id.toolbarPreferences);
setSupportActionBar(toolbarPref);
Second, set click listener and define bahaviour:
toolbarPref.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
Done.
I'm learning now Java with a book "Learning Java by building Android Games" from Packt Publishers by John Horton. I'm really newbie to OOP and I have learned C for one year. I do everything as it is in the book. After I have added setOnClickListener and tried to test my App, I see "the application was closed" instead running new Activity.
Could you please help me to find out what is wrong? The book is a little bit out of a date (Jan 2015) and I had to correct some initial code to make initial errors disappear.
package com.packtpub.mathgame;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.util.Log;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state");
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available");
/* initialize app */
}
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
}
===============
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="#+id/buttonPlay"
android:layout_marginTop="28dp"
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/imageView" />
1) You need to register the GameActivity In you AndroidManifest.xml like this
<activity
android:name=".GameActivity" />
inside the application tag
Just a note if these views arn't available your layout will look very wierd ;)
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_alignLeft="#+id/button2"
android:layout_alignStart="#+id/imageView"
Did you register GameActivity in your AndroidManifest.xml file ?
You should getId of your button onClick method only thn you can identity on which button you have click on , now you one
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonPlay:
//write your implementation here
Toast.makeText(this, "dsfdf", Toast.LENGTH_LONG).show();
break;
case R.id.buttonPlay1:
Toast.makeText(this, "sdsdsdsd", Toast.LENGTH_LONG).show();
break;
}
}
change this:
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
in this:
final Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
});
I'm a newcomer to Java and Android Studio so am still learning, so sorry if this question is simplistic. I have recently discovered that as an alternative to coding an onClickListener in the activity.java file to respond to a button click, it can be done more simply with an android:onClick="method name" in the corresponding layout.xml file. I have already looked at this site's questions relating to the pros and cons of each method, but that is not my problem. My problem is, where and how can I declare a text field that is used by two methods without having to declare it in each method?
The code that follows is as minimal as possible. There are two buttons and one text view. If I attempt to put "TextView themessage = (TextView) findViewById(R.id.message);" anywhere other than in both methods, I get the dreaded "Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference".
Is there anywhere and any way to make a single declaration that can be used by both methods without generating this exception?
Extract from the .xml file
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:id="#+id/topbutton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:onClick="doit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="***"
android:id="#+id/message"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Again"
android:id="#+id/againbutton"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="63dp"
android:onClick="starit"/>
Top end extract from the .java file
package com.example.owner.clickme;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("****");
}
.
. etc.
It is common practice in Android to instantiate any Views within the onCreate, or where you inflate the main content view.
So, make a field inside of MainActivity like so
private TextView themessage;
Within onCreate get the TextView
theMessage = (TextView) findViewById(R.id.message);
Then you are free to use theMessage across both methods.
All in all, it looks like this
public class MainActivity extends AppCompatActivity
{
private TextView themessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
themessage = (TextView) findViewById(R.id.message);
}
public void doit (View v)
{
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
themessage.setText("****");
}
}
I think what you want to do is have the TextField as member of your activity class.
Something like that probably
public class MainActivity extends AppCompatActivity {
TextView theMessage;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theMessage = (TextView) findViewById(R.id.message);
}
public void doit () {
theMessage.setText("Well clicked, Sir!");
}
public void starit() {
themessage.setText("****");
}
}
I know that this has been asked many, many times before, but how do I make my button play a sound when it's pressed?
this is my button's code:
<Button
android:id="#+id/c1"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:background="#drawable/button_selector" />
and here is my MainActivity.java:
package com.example.appname;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
what do I have to add to make my button play a sound? If it helps I'm using Eclipse.
EDIT
I don't really know what I'm doing when it comes to this, so if you could please show me what to add to my code that would be great.
You could use an OnClickListener. Here is the developer section detailing how to do it.
You need to implement the onClick method once you assign the OnClickListener to your button. Here is the section about buttons, the code here will get you started.
For playing the sound, I recommend a MediaPlayer You can set your MediaPlayer to start (playing) in the onClick method.
first of all you have to understand events generated by views in android ,in your case button click event, you have to use OnClickListener
and youre code look like
public class MainActivity extends Activity implements
OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnPlaySound = (Button) findViewById(R.id.c1);
btnPlaySound.setOnclickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.view_id:
break;
default:
break;
}
}
}
I have managed to successfully start two activities using the ImageButton along with .setOnClickListener tied to it, i have also included layouts with different ImageButtons. Each button launches an activity. I have created the activities. I have also managed to remover crash bugs, lint errors, have the latest Android SDK. However now the buttons stop working even though you hear the click. Neither the activity launches on the first imageButton nor the second one.
This happens the moment i put multiple ImageButtons in. It works with 1 button. I suspect the (this) command in the class is confused as to what to call. My intent call method to start new activities are streamlined and basic for quick, uncomplicated access.
Can someone please help me as to why the multiple setOnclickListener cannot be tied to the relevant imageButtons please?
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
ImageButton imageButton2;
ImageButton imageButton3;
ImageButton imageButton4;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
imageButton2=(ImageButton)findViewById(R.id.imageButton2);
imageButton3=(ImageButton)findViewById(R.id.imageButton3);
imageButton4=(ImageButton)findViewById(R.id.imageButton4);
imageButton1.setOnClickListener(this);
imageButton2.setOnClickListener(this);
imageButton3.setOnClickListener(this);
imageButton4.setOnClickListener(this);
}
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
If you notice I have only coded 2 of the four buttons (so once this code works in theory the others should).
This is what OtherActivity from imageButton1 calls.
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
and this is the activity imageButton2 calls
package com.example.startanotheractivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
public class OtherActivity2 extends Activity
implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_layout_2);
Intent intent = getIntent();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:background="#FFFFFF" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="566dp"
android:layout_height="456dp"
android:background="#null"
android:src="#drawable/gatanga1"
android:onClick="onClick1" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga2"
android:onClick="onClick2" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga3"
android:onClick="onClick3" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="540dp"
android:layout_height="189dp"
android:background="#null"
android:src="#drawable/gatanga4"
android:onClick="onClick4" />
</LinearLayout>
Thank you
Many many thanks.
use a switch statement in onClick method
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1: /** Start a new Activity OtherActivity.java */
Intent intent = new Intent(MainActivity.this, MyCards.class);
this.startActivity(intent);
break;
case R.id.imageButton2: /** Start a new Activity OtherActivity2.java */
Intent intent2 = new Intent(MainActivity.this, OtherActivity2.class);
this.startActivity(intent2);
break;
}
The onClick method passes the clicked view as an variable, you can use a switch statement to determine which view was clicked and then you can perform your operations..
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
Intent intent = new Intent(MainActivity.this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent = new Intent(MainActivity.this, OtherActivity2.class);
startActivity(intent2);
break;
}
}
Scholars, Educated Aristocrats and of course Plumbers.
Thank you for replying. It works now by the code i did, although i will try the above solutions. I have experimented with switches and i do like them. I want to make sure memory management and file sizes are kept to a minimum as the end app will have about 40 activities.
However the way i did it was i removed all the other ImageButtons declarations in MainActivity except:
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton imageButton1;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reusable_layout);
imageButton1=(ImageButton)findViewById(R.id.imageButton1);
}
The onClick methods then were left as onClick1,onClick2. Both activities worked. I added onClick3 and onClick4 like the below:
public void onClick1(View view) {
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
}
public void onClick2(View view) {
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
}
public void onClick3(View view) {
Intent intent =
new Intent(this, OtherActivity3.class);
startActivity(intent);
}
public void onClick4(View view) {
Intent intent =
new Intent(this, OtherActivity4.class);
startActivity(intent);
}
I think what seemed to happen then is the code wasnt confused or stuck in a loop (it didnt crash on my original posting). But instead now it goes straight to layout, gets the "onClick1" for button 1 and "onClick2" and matches them with the public void onClick(X) in MainActivity, because i have just declared i am using the ImageButton and an Intent, right after onClickListener, it works.
Note if i move around this code it breaks or will give me the same error. Regardless, i am happy it works but am intrigued as to why i did not have to declare all my buttons. Maybe it is just the logic in Java Code working.
I will definately try the switches and amendments later experimenting.
With best wishes.
in the MainActivity you should correctly implement OnClickListener interface:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.imageButton1:
Intent intent =
new Intent(this, OtherActivity.class);
startActivity(intent);
break;
case R.id.imageButton2:
Intent intent =
new Intent(this, OtherActivity2.class);
startActivity(intent);
break;
}
}