Adding more Buttons when a Button in clicked - android

Please look at the following algorithm and tell me if I can achieve it:
create a main_activity
inside the main_activity, create a simple Button
the Button is labeled as "Add Button"
once the users clicks the Button, an additional Button is created and placed in the Activity.
In other words:
once the user clicks on the add Button, it should create another Button and
place it under the "Add Button" Button.
I apologize in advance as this may be confusing, so please feel free to comment and ask for clarification.
I originally thought about creating a separate method, in which I would create a ButtonView, but I am not sure how I can physically create a Button.
Would I need to apply code to .xml file also?
I am really confused.
Here is my code:
MainActivity.java
package inc.fimp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addArm = (Button) findViewById(R.id.btnAddArm);
addArm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addButton();
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
int res_id = item.getItemId();
if(res_id==R.id.action_contact)
{
Toast.makeText(getApplicationContext(), "You selected Contacted us option", Toast.LENGTH_SHORT).show();
}
if(res_id==R.id.action_settings){
Toast.makeText(getApplicationContext(), "You selected Settings Option", Toast.LENGTH_SHORT).show();
}
return true;
}
public void addButton(){
// create an aditional button
}
}
xml file code
<?xml version="1.0" encoding="utf-8"?>
<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="inc.fimp.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_arm"
android:textStyle="italic"
android:id="#+id/btnAddArm"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/addarm"
android:singleLine="false" />
</RelativeLayout>

Start by adding an ID to the parent layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/buttonContainer"
Then, get that with findViewById. ViewGroup simply used because that is all you need to get the addView method.
public class MainActivity extends AppCompatActivity {
private ViewGroup rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = (ViewGroup) findViewById(R.id.buttonContainer);
Then, in the addButton,
Button button = new Button(MainActivity.this); // Need to provide the context, the Activity
// button.setText("Added!"); // for example
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, R.id.btnAddArm);
// params.addRule ... (there's a bunch you can add)
rootView.addView(button, params);
Since you have a RelativeLayout, you can also programmatically put LayoutParams to do layout above/below, etc. other views.

Related

Return text entered in textbox

I'm trying to work through the "Start Another Activity" tutorial but, having worked through the whole thing (twice), the app still refuses to return the text entered in the textbox - it always returns "Hello World".
I've tried to figure it out, and suspect it might be something to do with the fragment_display_message.xml, in which there is an EditText calling the Hello World string. But really I have no idea.
Any help would be appreciated. Here's the code:
MainActivity.java
package com.knargle.streetiteatit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.knargle.streetiteatit.MESSAGE";
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
fragment_main.xml
<LinearLayout 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:orientation="horizontal"
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="com.knargle.streetiteatit.MainActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
DisplayMessageActivity.java
package com.knargle.streetiteatit;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
fragment_display_message.xml
<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="com.knargle.streetiteatit.DisplayMessageActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/hello_world" />
</RelativeLayout>
In your DisplayMessageActivity.java file, you are calling setContentView twice which it-self is overwriting the first line of code. Currently your code looks like this:
setContentView(textView);
setContentView(R.layout.activity_display_message); // Delete this line. As this line of code appears in your java file, it is overwriting the 'text' you entered with the default 'hello world' message
It should be just like this:
setContentView(textView);
The setContentView is being called twice in DisplayMessageActivity. Remove the second one:
setContentView(R.layout.activity_display_message);
In your DisplayMessageActivity:
// Set the text view as the activity layout
setContentView(textView);
setContentView(R.layout.activity_display_message);
You call setContentView twice, which just overwrites what was already there. Remove the second setContentView.
You can follow the answers from both Andrew and Rajesh. But the fact that you have defined a layout fragment_display_message and I am sure you want to use it. In that case, all you need to do is get rid of the code to dynamically add the TextView and the correspodning setContentView and leave the second setContentView that uses your layout. Once done, you get the reference to your EditText and set it's text to what was sent in the Intent.
Remove these lines from DisplayMessageActivity :
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
You were attempting to set the message in a new text view which is not part of your layout file. And then setting that text View as the ContentView of your layout. That seems like a convoluted approach. Instead try the following :
After the setContentView(R.layout.activity_display_message); line, add these lines :
EditText editText = (EditText) findViewById(R.id.edit_message);
editText.setText(message);
This way, you use the existing Edit text element in your layout file to show the message. Your original code never replaced HelloWorld in this element. That is why it always shows you HelloWorld instead of your message.

How to make two diffrent Activities to use the same layout Android

Below code works fine, but it opens a new layout and shows the toast message. but i wanted it to show toast & popup menus on the current layout. I'm working on popup menu project, i want to show popup menu on same layout. Thanks in Advance.
MainMactivity.java
package com.example.twoact;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent openpopactivity = new Intent(MainActivity.this,
MainActivity2.class);
startActivity(openpopactivity);
}
});
}
}
MainActivity2.java
package com.example.twoact;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Handler;
public class MainActivity2 extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "ya am in",
Toast.LENGTH_SHORT).show();
}
}, 1000);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.twoact.MainActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="142dp"
android:text="Button" />
</RelativeLayout>
You can use Popup menu and Popup window. in this you can use your custom layout so you can get your view as window in same activity.
Popup window will be good option because it is since API LEVEL 1
please refer this docs and example 1,example 2
And Popup Menu is since API LEVEL 11. so you have to manage for lower version
docs for Popup Menu and example
popup window

crash when attempt to use onClick in xml to access a method within a function in a different class. How do I solve this?

Note: I realize that there are no onClick in the xml because every tim i try to link it to AlexRevolver.shoot() or .reload() the program crashes.
Any ideas on how to fix this, also the TextView's are not getting updated
Display.Java
package com.example.firedatgun_v2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class Display extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
}
#SuppressWarnings("unused")
public void main(){
gun AlexRevolver = new gun(0);//create a new gun Object
Button reload_V = (Button) findViewById(R.id.reload_B);
Button fire_V = (Button) findViewById(R.id.fire_B);
TextView bulletCount_V = (TextView)findViewById(R.id.bulletCount_TV);
TextView infoDisplay_V = (TextView)findViewById(R.id.info_TV);
infoDisplay_V.setText("Magazine Size: " + AlexRevolver.magSize);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
}
gun.Java
package com.example.firedatgun_v2;
import android.app.Activity;
import android.widget.TextView;
public class gun extends Activity{
public TextView bulletCount_Var = (TextView)findViewById(R.id.bulletCount_TV);
public TextView infoDisplay_Var = (TextView)findViewById(R.id.info_TV);
public int magSize = 6; //create the variable called "magSize" //set the size of the Magazine to 6
public int bulletCount; //create a variable called "bulletCount"
public gun(int startingBullets) {
bulletCount = startingBullets;
}
public void reload(){
bulletCount = magSize;
}
public void shoot(){
if (bulletCount < 0){
infoDisplay_Var.setText("Bang!");
bulletCount --;
bulletCount_Var.setText(bulletCount);
}
else{
infoDisplay_Var.setText("Reload now");
}
}
}
activity_display.xml
<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=".Display" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="#string/bullets_in_mag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="35sp" />
<TextView
android:id="#+id/bulletCount_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="#string/empty"
android:textSize="50sp" />
<TextView
android:id="#+id/info_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="86dp"
android:text="#string/clear" />
<Button
android:id="#+id/fire_B"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/info_TV"
android:layout_marginTop="31dp"
android:layout_toLeftOf="#+id/info_TV"
android:text="#string/Fire" />
<Button
android:id="#+id/reload_B"
android:layout_width="150sp"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/fire_B"
android:layout_alignBottom="#+id/fire_B"
android:layout_toRightOf="#+id/info_TV"
android:text="#string/reload" />
</RelativeLayout>
if you need more data, just post , any help would be greatly appreciated.
Only when a activity A calls setContentView with a layout a, then that activity A can directly access the elements in the layout a using the findViewById() - means layout elements can be used directly by that activity A - or in other words*layout a* elements will not be directly accessible to activity B through findViewById().
Also Which means that for the events directly set in layout a, when fired will always look for a matching function in the activity A in which that layout was inflated through setContentView.
In your case Activity gun is not the activity that inflated the *layout activity_display* instead Activity Display inflated that layout. so for any events directly specified in *layout activity_display*,when triggered will look for matching function in the Activity Display - if a match is absent error will be raised
Modified Code
Display.java
....
...
public class Display extends Activity {
gun AlexRevolver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
AlexRevolver = new gun(0)
AlexRevolver.reload_V = (Button) findViewById(R.id.reload_B);
AlexRevolver.fire_V = (Button) findViewById(R.id.fire_B);
AlexRevolver.bulletCount_V = (TextView)findViewById(R.id.bulletCount_TV);
AlexRevolver.infoDisplay_V = (TextView)findViewById(R.id.info_TV);
AlexRevolver.infoDisplay_V.setText("Magazine Size: " + AlexRevolver.magSize);
AlexRevolver.reload_V.setOnClickListener(AlexRevolver);
AlexRevolver.fire_V.setOnClickListener(AlexRevolver);
}
gun.java
gun can be an simple class instead of extending Activity
.....
.....
public class gun implements OnClickListener {
public TextView bulletCount_V;
public TextView infoDisplay_V;
public Button fire_V;
public Button reload_V;
public gun(int startingBullets) {
bulletCount = startingBullets;
}
.....
.....
...
public void onClick(View v)
{
switch(v.getId())
{
case R.id.reload_B:
this.reload();
break;
case R.id.fire_B:
this.shoot();
break;
}
}
}
Note: The above code does not follow proper oop, Java Interfaces can be used to achieve the same functionality
You have two activities in your posted code as both extends Activity: gun and Display. And you can't instantiate the activity like any other java object. There are certain protocols you have to follow for communication between activities. But from you posted code you don't need multiple activities.
Moreover, each activity on creation, instantiate the layout and that instance of the layout (and subelements as well) belongs to instance of that activity.
Android has good documentation on layout
You have
public class gun extends Activity{
public TextView bulletCount_Var = (TextView)findViewById(R.id.bulletCount_TV);
You will get NullPointerException. findViewById looks fora view with the id mentioned in the current inflated layout.
Also in Display Activity you do not call main().
Change your activity code to
public class Display extends Activity implements OnClickListener {
TextView bulletCount_Var,infoDisplay_var;
Buttom reload_V,fire_V;
public int bulletCount=0; // initially count is 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
reload_V = (Button) findViewById(R.id.reload_B);
fire_V = (Button) findViewById(R.id.fire_B);
bulletCount_Var = (TextView)findViewById(R.id.bulletCount_TV);
infoDisplay_Var = (TextView)findViewById(R.id.info_TV);
infoDisplay_V.setText("Magazine Size: " + AlexRevolver.magSize);
realod_V.setOnClickListener(this);
fire_V.setOnClickListener(this);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.reload_B :
// do reload calculation
// update bulletCount_Var
break;
case R.id.fire_B :
// do fire calculation
// update infoDisplay_Var
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display, menu);
return true;
}
}
Write button listeners. Do calculation and update text view in activtiy. I do not knwo why you use gun class which extends Activity.

Unfortunately (project name) has stopped working on button click

An area which will present a predefined question
A button which will cause the answer to the question to be shown while leaving the question on the screen
An area which will present the answer
A button which will cause a transition to a screen that is formatted the same as this one, with the next question shown on it
A button which will cause the app to end (a transition to (3))
Only trying to get the transition from screen 1 to screen 2 to work with a different question/answer pair in its place with a button click. If there is anyway to do this other than switching the screens and activities which is the error, please let me know.
package com.example.androidassignment2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class AndroidAssignment2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_assignment2_1);
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.android_assignment2_1, menu);
return true;
}
}
layout file
<LinearLayout 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:orientation="vertical" >
<TextView android:id="#+id/Questions"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:text="#string/Q2" />
<Button android:id="#+id/QButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_question" />
<Button android:id="#+id/AButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send" />
<TextView android:id="#+id/Answers"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:hint="#string/A2" />
<Button android:id="#+id/QuitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_quit" />
</LinearLayout>
activity 1 file (incase needed)
package com.example.androidassignment2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivityForResult(myIntent, 0);
You are starting a new activity, the most likely cause is that this is has not been declared in the Manifest.
In your AndroidManifest.xml`, you will need to add something like this:
<activity
android:name="your.package.name.AndroidAssignment2_1" />
This will reside inside of the <application> tag.
You are using startActivityForResult() but you don't override the onActivityForResult() method in your first Activity. You could change that to just use startActivity() and remove setResult() from your second Activity.
Button next = (Button) findViewById(R.id.QButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), AndroidAssignment2_1.class);
startActivity(myIntent);
}
});
If this isn't your problem then please post logcat (always when you have a crash) and make sure the Activity is decalred.
As far as your other inquiry
If there is anyway to do this other than switching the screens and activities which is the error, please let me know.
If you are simply changing the text then you can stay in the same Activity and change the text of your TextViews. You could store questions and answers in something like Arrays or in a DB if you wish and keep a counter to where you are and change the text with each click.
Another option, which may go along with the first if you want, is to use a ViewPager

Android - Show image from res/drawable onClick

First of all, I wanna say I've been seeking for an answer on the Forum and I found didn't match for what I wanted. Basically, what I want is: when the user clicks on one of the images previously "specified" on the .xml file, a new image is displayed on the center of the screen that is not "specified" on the .xml file. I wrote "specified" cause idk if it's the correct way to refer to this.
EDIT: there was no need to not specify the image previously, all I needed was to set "gone" for visibiity. This code is working exactly how I wanted (ty guys):
Main.java
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class Principal extends Activity {
ImageView cuia1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
cuia1 = (ImageView) findViewById(R.id.cuia1);
cuia1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ImageView cuia1grande = (ImageView) findViewById(R.id.cuia1grande);
cuia1grande.setVisibility(1);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.principal, menu);
return true;
}
}
activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*">
<TableRow
android:id="#+id/tabelaCuias"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center">
<TextView
android:id="#+id/selecionaCuia"
android:text="Selecione a cuia"
android:textStyle="bold">
</TextView>
<ImageView
android:id="#+id/cuia1"
android:src="#drawable/cuia1">
</ImageView>
<ImageView
android:id="#+id/cuia2"
android:src="#drawable/cuia2">
</ImageView>
<ImageView
android:id="#+id/cuia3"
android:src="#drawable/cuia3">
</ImageView>
<ImageView
android:id="#+id/cuia4"
android:src="#drawable/cuia4">
</ImageView>
</TableRow>
</TableLayout>
<ImageView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_centerInParent="true"
android:visibility="gone"
android:id="#+id/cuia1grande"
android:src="#drawable/cuia1grande">
</ImageView>
Is there any reason you don't want to "specify" the image in your layout file? You could place it there and not display it (visibilty="gone"), and then show/hide it when you deem fit.
Here's what I'd do:
Make your layout a RelativeLayout instead of a TableLayout (this will make things easier for showing the image in the center)
Place your TableLayout within the wrapping RelativeLayout
Define an ImageView as the last child within the wrapping RelativeLayout, set centerInParent="true", visibilty="gone"
In your onClick method, simply set its visibility as visible.
If you really don't want to define the ImageView in the layout, then you can create it programmatically:
Follow the same steps 1-2 as before
Capture the reference to the wrapping RelativeLayout in the code
In the onClick method, create the ImageView programatically, specifying the centerInParent="true" via the code (let me know if you want an example on how to do this & I'll edit the answer with a code sample).
Add the new view to the RelativeLayout via myRelativeLayout.addView(myImageView);
Hope this helps :)
public class Principal extends Activity {
ImageView cuia1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
cuia1 = (ImageView) findViewById(R.id.cuia1);
//set invisible
cuia1 .setVisibility(View.INVISIBLE);
cuia1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//show image on the center of screen
//set image
cuia1.setImageResource(R.drawable.cuia1);
// set visible
cuia1 .setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.principal, menu);
return true;
}
}
import import android.view.View;
Cheerz!

Categories

Resources