Using onClick in button to a view - java

Just started learning Android this morning, need help on this. I have few buttons in my App, I want when a user clicks a button a image will be shown and back button to load main.xml .
Code:
In main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_marginTop="40dp"
android:layout_width="100dp"
android:layout_height="80dp"
android:id="#+id/b1"
android:text="xyz"
android:background="#ff3375"
android:layout_marginLeft="20dp"
/>
<Button
android:layout_marginTop="40dp"
android:layout_width="100dp"
android:layout_height="80dp"
android:id="#+id/b2"
android:layout_toRightOf="#id/b1"
android:text="abc"
android:background="#ff3375"
android:layout_marginLeft="80dp"
/></RelativeLayout>
And in Activity.java
package com.sam;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class A2Activity extends Activity {
/** Called when the activity is first created. */
Button a,b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
a= (Button) findViewById(R.id.b1);
b= (Button) findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});}}
Now, what do I need to add inside the onCLick method to open a image or a XML file and also a back button to return to main.xml

please explain your question a little further . what do you mean open an image or xml file? do you mean to create a bitmap ? do you mean to show it? if so , where? also , what do you mean that the back button will return to main.xml? main.xml is a layout file , not an activity .
in any case, maybe you meant that you wish to open an image in full screen upon pressing on the button ,and when clicking on the back button of the device go back to the activity you've created?
if so , you can create a new class that extends Activity , update the manifest so that it would be reachable , and start it (using startActivity) . in the new activity class , set the content view to be of an ImageView that shows an image , or of a layout file that has an imageView that shows an image .
for starting a new activity , you need to call :
startActivity(new Intent(CurrentActivity.this, NewActivity.class);
where "CurrentActivity" is the current activity that you are at (called "A2Activity" in your sample) and "NewActivity" is the one that shows the image.
as written before , do not forget to update the manifest.

Related

Android start new activity when clicking widget

I am new with coding Java and xml for android applications and I wanted to know how I start/open a new activity when clicking on something. In this case I am using a relative layout to keep a image and text together as one object. What I want to do is when you click on it it will start/open the new activity. How do I do this? Could someone tell me step by step since I am quite new to this.
First of all, if you want your layout to act (RelativeLayout) like a button (do not handle onClick on layout child components) firstly set in your xml layout file RelativeLayout attribute
android:clickable="true"
Or you can do this directly in your code (in onCreate method)
relativeLayout.setClickable(true);
Than you need to set onClickListener for your layout.
You can do this simply by creating anonymous class
relativeLayout.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent startActivityIntent = new Intent(getApplicationContext(),YourDesiredActivity.class);
startActivity(startActivityIntent);
}
}
UPDATE
Layout is defined in xml file, of course in Android you can do this in code ,but it is better to use xml file.
In your IDEA you have folder res->layout here you should place your layout files. For example layout with name `
relative_root_layout.xml
<xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_layout"
android:layout_height="wrap_content" android:layout_width="wrap_content">
<ImageView
android:id="#+id/image_view">
android:layout_width="wrap_content"
android:src="#drawable/icon"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
ImageView>
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_toRightOf="#+id/image_view"
android:text="Relative layout">
TextView>
RelativeLayout>
But in case you have only text and image it is better to use
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#android:drawable/btn_image"
android:text="Button with Image"
android:gravity="left"
android:drawablePadding="10dp">
Button>
How you can access your widgets ?
This is very basic thing you have to know if you are developing for android, this is essential part. Please read documentation, read books, watch tutorial or whatever.
In short you need to inflate layout in activity onCreate() method
RelativeLayout mRelativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_root_layout);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
mRelativeLayout.setOnClickListener(.....)
}
But again this very basic things you must know.
You could set onClickListener for any of your views.
ImageView image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Youractivity.this, Moveactivity.class));
}
});
Starting a new activity is done by creating an Intent and then calling startActivity, e.g.
Intent intent = new Intent(context, AnotherActivity.class);
context.startActivity(intent);
You can wrap this code in an OnClickListener as other answerers already suggested.
A second option is to add an android:onClick attribute to your RelativeLayout
<RelativeLayout ...
android:onClick="clickMe">
<ImageView .../>
<TextView .../>
</RelativeLayout>
and in your activity
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clickMe(View notused) {
Intent intent = new Intent(this, AnotherActivity.class);
this.startActivity(intent);
}
}
See startactivity for a complete example.

How do i create a button to another page for my app

i was just wondering how i would make a button on my page so that it would go to another page for my app. I am a beginner so if you could explain how it all works and where it goes it would help a lot.
PS i am using android studio if that makes a difference and this is the code i have so far in my fragment_main.xml. I have not entered any code into the .java
<TextView android:text="#string/hello_world"
android:id="#id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/homebutton"
android:layout_below="#+id/text"/>
You can declare views and objects dynamically in Java, and then pass the button from fragment to fragment (or Activity to Activity, depending on your app).
To declare a Relative Layout with a Button, for example:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
public class JavaLayoutActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = new Button(this);
RelativeLayout myLayout = new RelativeLayout(this);
myLayout.addView(myButton);
setContentView(myLayout);
}
This doesn't set the properties or anything, I am just using this as proof of concept.
XML makes things easy with regards to user interface design because you don't have to manage it in code, but this is one case where it is an exception. If you want dynamic interface objects, you need to use Java.
Instead of creating view dynamically you should obtain your view in activity
ImageButton button = (ImageButton) findViewById(R.id.firstButton)
and assign an onClick listener to id
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// start new Activity here
}
});
You can also do it in xml:
<ImageButton
android:id="#+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/homebutton"
android:onClick="sendMessage"
android:layout_below="#+id/text"/>
with such configuration, you should add method in activity:
public void sendMessage(View view) {
// start another activity here
}
There are two methods available in android using which you can go from one Activity to another.
1. Use button.setOnClickListener()
Create a button in xml file.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
Now set event listener for the button in your .class file
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the event you want to perform when button is clicked
//you can go to another activity in your app by creating Intent
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}
});
2. Use <android:onClick="goNext">
Put the onClick as the attribute of the button you have created in xml file.
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="goNext" />
Now in your .class file define an event for that button as,
goNext() {
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}

Hardware back button does not bring me back to previous page

I have 2 xml pages, from the main page after clicking the next button it goes to the second page, but when I press on the hardware back button. It does not goes back to the main page.
How do I add the code for the hardware back button?
Testing on Android 4.3.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Main Page" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="Go to Page 1" />
</RelativeLayout>
java class :
package com.example.linktestfyp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_VIEW);
myIntent.setData(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
setContentView(R.layout.main1);
Toast.makeText(getApplicationContext(), "Button 1 clicked",
Toast.LENGTH_LONG).show();
}
});
}
}
to navigate between activities you should call startActivity(intent); and not changing the contentView of the Same activity.
you should create two activities : Activity1(which will display the main.xml layout) and Activity2(which will display the main1.xml layout) , and while the user is in the Activity2 and press the back button , the Activity1 will be shown again automatically by the system, and the Activity2 will be destroyed.
Example :
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivity(intent);
see this tutorial about how to switch between activities with a demo sample application which you can download at the end of the tutorial .
NB: don't forget to declare your activities in the Manifest file.
This may help you ..
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
//do your stuff
}
return super.onKeyDown(keyCode, event);
}
You probably want two activities (see below). When you click on the button of MainActivity, the MainActivity1 will start and display the R.layou.main1 layout. If you click the back button, the MainActivity1 will destroy, and the MainActivity will resume (by default, so you don't need to program this)
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, MainActivity2.class));
}
}
}
public class MainActivity1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
}
}
You are not changing activities so when you back press the 1st page is not shown to you,
you should use setcontentview in onbackpressed() method,
then you will be able to show the 1st page otherwise it will always go to the previous activity which is not what you are looking for it seems.

Programmatically close dialog opened by theme.dialog

I have two xml files, and two java files. In the first xml I have few buttons, and one of them is EXIT. In the java file i write in the onCreate:
Button exitButton = (Button) this.findViewById(R.id.button_exit);
exitButton.setOnClickListener(this);
Then further down the code I write:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_exit:
Intent switchtoExit = new Intent(StartActivity.this, ExitActivity.class);
startActivityForResult(switchtoExit, MESSAGE_REQUEST);
break;
}
}
the second java files is called ExitActivity.java. In the manifest file I wrote:
<activity android:name=".ExitActivity"
android:label="#string/exit_title"
android:theme="#android:style/Theme.Dialog"/>
In order to make the second xml file popup like a dialog.
My second java file is(the one that popup like a dialog):
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ExitActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_exit);
Button noExitButton = (Button) this.findViewById(R.id.exit_no_button);
noExitButton.setOnClickListener(this);
Button yesExitButton = (Button) this.findViewById(R.id.exit_yes_button);
yesExitButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.exit_no_button:
Toast.makeText(this, "Good Choice :-D", Toast.LENGTH_SHORT).show();
break;
case R.id.exit_yes_button:
Toast.makeText(this, "So sad... \nnice playing with you...", Toast.LENGTH_SHORT).show();
break;
//break;
}
}
}
and my second java file has:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/red">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/exitTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/exit_body"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/exit_no_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/exit_no_button"
android:layout_weight="1.0"
/>
<Button
android:id="#+id/exit_yes_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/exit_yes_button"
android:layout_weight="1.0"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
What I wanted to do is to have one button close the dialog, and the other button to stop the application. I tried finish(), and it worked just fine. but then when I added the onDestroy() method one button would restart the application, and the other just close it. Also, when I pressed the Back button, it would close the application.
Can anyone explain me how to get the following to happen:
When the dialog pops up, and I press the back button, it just closes the dialog?
When I press on exit button, it closes the application.
When I press on the Stay button it closes the dialog.
Thanks
You're doing this the wrong way. Using a second activity is overkill. Use an AlertDialog, which you can easily make with AlertDialogBuilder. Set it to have a positive and a negative button. Set an OnClickListener for the positive button that calls finish on the only activity. There you go- 1 activity, and the dialog class itself will take care of popping up and closing itself.

My app is unable to start activity?

When i try to run the app on my phone,it force closes when i try to do activity 3.
Logcat says:
01-13 17:53:25.368: E/AndroidRuntime(3235): Caused by: java.lang.NullPointerException
01-13 17:53:25.368: E/AndroidRuntime(3235): at android.app.activity3.onCreate(activity3.java:18)
where line 18 is
Button wg = (Button) findViewById(R.id.Back);
heres my full code for activity3.java:
package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class activity3 extends Activity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main3);
Button wg = (Button) findViewById(R.id.Back);
wg.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
}
Thanks in advance
You need to modify your xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<!-- your textview -->
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/text1"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<!-- your back button -->
<Button
android:id="#+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/Back"
/>
</RelativeLayout>
What I did:
Removed text and orientation from your root RelativeLayout, these do nothing.
Modified your height and width, feel free to change these as you please.
Added a Button with id of R.id.back and text of #string/Back.
You will now be able to reference your button using findViewById(R.id.back) and set your click listener.
I don't see a button in the xml. And once you have that, it needs to have:
android:id="#+id/Back"
This is happening because you don't have a button declared in your view. Only a Textview. You must create the button in the view. You're referencing nothing hence the null.
You can find a nice example of how to make a button here.
You don't have button with id "Back" in xml posted, that is why you are getting null there. Add button entry in your xml.

Categories