Pass ImageButton Value - android

I'm brand new to android and trying to create an activity that has a fragment inside it. The idea is the fragment has 3 ImageButtons. The ImageButton you click will pass it's image to the activity and then show it in another fragment created after the onClick (full screen ImageView) within the main activity. The problem is I can't figure out how to pass the information. I've read over multiple questions already asked similar to this one, and went over android developers website but the more I read the more confusing it becomes. I'm also running into the problem of findViewById saying it cannot resolve the method. I have no idea why it is telling me this and have tried many things to fix it, nothing is working. Here is my code and any suggestions would be appreciated.
Main Activity:
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements MainActivityFragment.CanPassData{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void passData(int value){
MainActivityFragment fragment = new MainActivityFragment();
fragment.setData(5);
getSupportFragmentManager().beginTransaction().add(R.id.fragment, fragment).commit();
//***Taken From Android Developer, I believe this is how you create a new fragment when you pass the data to the main activity****
if (fragment != null) {
fragment.getData();
} else {
MainActivityFragment newFragment = new MainActivityFragment();
Bundle args = new Bundle();
//******No idea what this is calling, pictureChosen and picture are default values taken from the website*******
args.putInt(MainActivityFragment.pictureChosen, picture);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
//*****************************************************************************************
}
public void processData(){
MainActivityFragment fragment = (MainActivityFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
int value = fragment.getData();
}
}
Fragment:
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivityFragment extends Fragment implements View.OnClickListener {
private int data;
private CanPassData parent;
public interface CanPassData{
public void passData(int value);
}
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//***findViewById is saying it cannot resolve below
setContentView(R.layout.fragment_main);
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton);
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
//******************************************************************************************
return inflater.inflate(R.layout.fragment_main, container, false);
}
public void onAttach(MainActivity activity){
parent = (CanPassData) activity;
}
public void setData(int value){
data = value;
}
//***onClick also has all findViewByID as cannot resolve method, and i'm not exactly sure what to do within each case, the stuff I have in there was also taken from android developer.
#Override
public void onClick(View v){
switch (v.getId()) {
case R.id.imageButton:
ImageView box = (ImageView)findViewByID(R.id.imageButton);
Drawable name = box.getBackground().getCurrent();
Intent intent = new Intent (this, newFragment.class);
intent.putExtra("com.example.coding.assignment2", name);
startActivity(intent);
break;
case R.id.imageButton2:
box = (ImageView)findViewByID(R.id.imageButton2);
name = box.getBackground().getCurrent();
intent = new Intent (this, newFragment.class);
intent.putExtra("com.example.coding.assignment2", name);
startActivity(intent);
break;
case R.id.imageButton3:
box = (ImageView)findViewByID(R.id.imageButton3);
name = box.getBackground().getCurrent();
intent = new Intent (this, newFragment.class);
intent.putExtra("com.example.coding.assignment2", name);
startActivity(intent);
break;
}
}
public void pushData(){
parent.passData(data);
}
public int getData(){
return data;
}
}
A lot of the methods such as getData and pushData I'm not exactly sure how to use to get the info to the main activity, it was information given to me during class. I am wondering if there is a way to just pass the drawable itself if it is clicked, then assign that drawable to a ImageView in the new fragment that displays it covering the entire fragment. I've been told I need to make a 2nd fragment xml, but the java file itself should be created via the main activity. Is this correct?

You cannot resolve the findViewById because you have to inflate a View in order to use Fragments findViewById, like this:
View v = inflater.inflate(R.layout.fragment_main, parent, false);
ImageButton button1 = (ImageButton) v.findViewById(R.id.imageButton);
ImageButton button2 = (ImageButton) v.findViewById(R.id.imageButton2);
ImageButton button3 = (ImageButton) v.findViewById(R.id.imageButton3);
//call your button.setOnClickListener
return v;
There is no need to call setContentView()
In the onClick(View v) you also need to call v.findViewById()
Also you decleare your variables in a case, you should declare them before any of the case if you want to use them that way. It should look something like this:
public void onClick(View v){
ImageView box=null;
Drawable name = null;
Intent intent = null;
switch(v.getId()){
case R.id.imageButton:
box = (ImageView) v.findViewByID(R.id.imageButton);
name = box.getBackground().getCurrent();
intent = new Intent (this, newFragment.class);
intent.putExtra("com.example.coding.assignment2", name);
startActivity(intent);
break;
And so on

Related

how to open new activities from fragment class using multiple buttons?

I have this fragment activity called BmiFragment from Navigation Drawer using Sliding Menu, from which i want to go to a new activity i.e. BmiCalculator.class to perform some task but i am not able to do so. I am trying to do this by implementing onclicklistener to the fragment activity. In the XML layout there is simply four buttons by clicking on them i want to open a new activity to perform certain task. Please provide me some help. Click here to view for errors
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class BmiFragment extends Fragment implements OnClickListener {
public BmiFragment() {
}
Button btn, btn1, btn2, btn3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bmi, container,
false);
btn = (Button) rootView.findViewById(R.id.button1);
btn.setOnClickListener(this);
btn1 = (Button) rootView.findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2 = (Button) rootView.findViewById(R.id.button3);
btn2.setOnClickListener(this);
btn3 = (Button) rootView.findViewById(R.id.button4);
btn3.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Intent intent = new Intent(this, BmiCalculator.class);//***ERROR: The constructor Intent(BmiFragment, Class<BmiCalculator>) is undefined***//
startActivity(intent);[enter image description here][1]
break;
case R.id.button2:
break;
case R.id.button3:
break;
case R.id.button4:
break;
default:
break;
}
}
}
Intent intent = new Intent(this, BmiCalculator.class);//ERROR: The constructor Intent(BmiFragment, Class) is undefined//
startActivity(intent);[enter image description here]
instead of this use
Intent intent = new Intent(getActivity(), BmiCalculator.class);
startActivity(intent);

fragments - how to use them with activities that require actions?

First - apologies for the newbie question.
I'm trying to implement a Navigation Drawer that will be used across my app. To start, I've followed the Android tutorial and created a basic navigation which changes a with Fragments.
I can pass a framelayout id and fragment to FragmentTransaction. It works great.
I decided to create a new login activity with the default android files (In Android Studio: going to new - activity - login activity ). This is what's confusing me. My questions are:
Can I create a fragment of the login activity where the actions in LoginActivity will work? It looks like the fragment will create a view based on the layout passed, but the methods used in LoginActivity won't work?
If creating a fragment does not work for the login activity, what would be the cleanest way to ensure the navigation works when switching activities? The Navigation Drawer only works when on the main activity; switching to other activities (via Intent) causes the app to lose the navigation drawer actions. The image of the actionbar/navigation drawer remains.
Here's some of my code in MainActivity ... maybe I'm missing something that is causing the navigation drawer to stop functioning when switching activities by Intent?
(Note: LoginActivity extends MainActivity in the LoginActivity class)
Thanks in advance for any direction / advice!
public class MainActivity extends ActionBarActivity {
private NavigationDrawerFragment mNavigationDrawerFragment;
//USER DATA
public String mUserID;
public String mToken;
public String mProgramData;
//NAVIGATION DRAWER
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mActionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// get list items for nav
mTitles = getResources().getStringArray(R.array.nav_menu);
//drawer widget
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//listview of left drawer
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set up the drawer.
mDrawerList.setAdapter(new ArrayAdapter<>(this,
R.layout.drawer_list_item, mTitles));
//set onclicklistener on the each list item of menu options
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// some styling...
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//enables action bar app behavior
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ties drawerlayout and actionbar for navigation drawers
mActionBarDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
// different titles for the drawer actions
public void onDrawerClosed(View drawerView) {
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// set drawer toggle as the drawer listener
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#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 (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(id) {
case R.id.action_home:
Intent home = new Intent(this, MainActivity.class);
this.startActivity(home);
break;
case R.id.action_login:
Intent login = new Intent(this, LoginActivity.class);
this.startActivity(login);
break;
}
return super.onOptionsItemSelected(item);
}
EDIT
Thanks for your help so far in guiding me with my issue.
Unfortunately I don't think I'm asking the right question, but maybe viewing the LoginActivity code from Android Studio would help.
This is part of LoginActivity:
public class LoginActivity extends MainActivity implements LoaderCallbacks<Cursor> {
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mUserIDView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUserIDView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
getLoaderManager().initLoader(0, null, this);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUserIDView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mUserIDView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address or ID.
if (TextUtils.isEmpty(email)) {
mUserIDView.setError(getString(R.string.error_field_required));
focusView = mUserIDView;
cancel = true;
} else if (!isEmailValid(email) && !isIDValid(email)) {
mUserIDView.setError(getString(R.string.error_invalid_email));
focusView = mUserIDView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isIDValid(String email) {
//TODO: Replace this with your own logic
return email.length() == 6;
}
[continued]...........
I'll create a simple fragment of LoginActivity called menu1_Fragment:
public class menu1_Fragment extends android.support.v4.app.Fragment {
View rootview;
public View onCreateView(LayoutInflater inflater, ViewGroup view, Bundle savedInstanceState) {
rootview = (ViewGroup)inflater.inflate(R.layout.activity_login, null);
return rootview;
}
}
If i'm correct (hopefully I'm wrong!) the fragment is replaced with the View (menu1_Fragment). The View cannot have actions (like clicking the login button to send a httppost request).
Also, could you explain why onOptionsItemSelected in MainActivity breaks the navigationdrawer (drawer becomes unclickable. also cannot swipe right to pull it up). Intent launches an activity (LoginActivity), but only the drawer in apperance shows.
to hide also ActionBar icons you can do like:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
To replace main fragment when you click an item from the drawable menu list i see you have used selectItem(position) method, however that method is never declared on your code. To do that also you can do something like:
private void selectItem(int position){
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 1:
fragment = new TestFragment();
break;
case 2:
fragment = new TestFragment2();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
setTitle(navMenuTitles[position]);
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
I am giving you a example with multiple activities defined as fragment and called using MainActivity, Hope you will get your solution among it..
MainActivity.java
package com.example.fragmentdemo1;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
MainActivity activity;
private ListView lv;
private ArrayList<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
lv = (ListView) findViewById(R.id.listView);
list.add("First");
list.add("Second");
list.add("Third");
list.add("Forth");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
Fragment1 f1 = new Fragment1();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.container, f1).commit();
break;
case 1:
Fragment2 f2 = new Fragment2();
FragmentTransaction transaction2 = getSupportFragmentManager()
.beginTransaction();
transaction2.addToBackStack(null);
transaction2.replace(R.id.container, f2).commit();
break;
case 2:
Toast.makeText(activity, "" + position, 1000).show();
Fragment3 f3 = new Fragment3();
FragmentTransaction transaction3 = getSupportFragmentManager()
.beginTransaction();
transaction3.addToBackStack(null);
transaction3.replace(R.id.container, f3).commit();
break;
case 3:
Fragment4 f4 = new Fragment4();
FragmentTransaction transaction4 = getSupportFragmentManager()
.beginTransaction();
transaction4.addToBackStack(null);
transaction4.replace(R.id.container, f4).commit();
break;
default:
break;
}
}
#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();
switch (id) {
case android.R.id.home:
finish();
break;
default:
break;
}
return false;
}
}
Fragment1.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment1 extends android.support.v4.app.Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView1);
view = (ViewGroup) inflater.inflate(R.layout.fragment1, null);
return view;
}
}
Fragment2.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView2);
view = (ViewGroup) inflater.inflate(R.layout.fragment2, null);
return view;
}
}
Fragment3.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment3 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView3);
view =(ViewGroup)inflater.inflate(R.layout.fragment3, null);
return view;
}
}
Fragment4.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment4 extends Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView4);
view = (ViewGroup)inflater.inflate(R.layout.fragment4, null);
return view;
}
}
NOTE : If you want to use method from Fragment class to MainActivity, then you can make it public static, and you can use that method directly by it's class name like Fragment1.countData().
This demo also apply for Navigation drawer.

Eclipse 4 errors

These are the error messages I get:
Cannot cast from an int toEditText
EXTRA_MESSAGE cannot be resolved to variable
PlaceholderFragment cannot be resolved to type
The nested type DisplayMessageActivity cannot hide an enclosing type
This is my code
package com.example.thirdapp;
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 {
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) (R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
You need to find the edit text view by id.
EditText editText = (EditText) view.findViewById(R.id.edit_message);
You need put the function "sendMessage" out of "PlaceholderFragment".
Here is mine:
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);
}

Buttons in a fragment android

I have this fragment that inflates an activity with buttons. How do I make the buttons go to another activity or fragment? the button 1 is supposed to go to a map activity and the button 2 a listfragment
EDIT**
All I want is one activity with 2 buttons and one of the buttons go to a fragment
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//context = getApplicationContext();
Button test= (Button)findViewById(R.id.testbtn);
test.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, MyLocation.class);//this works
startActivity(intent);
}
});
Button proximityAlert= (Button)findViewById(R.id.alertbtn);
proximityAlert.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this, mfragment.class);//this doesn't work, this class is a fragment list
startActivity(intent);
}
});
}
#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;
}
}
mfragment class
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.support.v4.app.ListFragment;
public class mfragment extends ListFragment {
String[] cities = {
"hello",
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setting the adapter to the layout
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1,
cities));
}
public void onListItemClick(ListView parent, View v, int position, long id) {
//displays a toest of the selected item in the list
//using an array to and using the position of the selected item
Toast.makeText(getActivity(),
"You have selected " + cities[position],
Toast.LENGTH_SHORT).show();
String selectedCity = cities[position];
/*//cheks if the detailfragment is in the current activity
DetailFragment detailFragment = (DetailFragment)
getFragmentManager().findFragmentById(R.id.detailFragment);
//---if the detail fragment is not in the current activity as myself---
if (detailFragment != null && detailFragment.isInLayout()) {
//---the detail fragment is in the same activity as the master---
detailFragment.setSelectedCity(selectedCity);
//calls the method set selected city and sends a string with the selcted city
} else {
*/
//---the detail fragment is in its own activity---
//this is only needed if is in portrait mode
//starts a new activity and it pass arguments to know
//which city got selected
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("city", selectedCity);
startActivity(intent);
//}
}
}
You need to specify the buttons in the correct layouts. If you want one button to be in the activity, you need to specify it in the activity's layout xml file. You will then use it from the activity's code. Likewise, you need to specify the button you want to be in the fragment in the fragment's xml layout file.
You cannot mix the layouts from activity and fragment, each one functions independent of each other and doesn't have direct access to each other.
I'm sorry to say this, but you are way far from what you want. Check this example: http://developer.android.com/guide/components/fragments.html#Example

Action Bar Sherlock, Load new activity OnClick

Afternoon.
Basically im using action bar sherlock as my navigation through fragments, one of my fragments layouts consists of four images with buttons underneath, the problem im having is i want to be able to switch to a different activity or XML layout. on the button click. I've tred many different ways to achieve this with no result
Ive got as far as the button click is registered by the device after the app is loaded up but im stuck on were to go for my switch and case code to load up a new layout.
package com.westcheshirecollege;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment implements OnClickListener{
Button button;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.home, container, false);
Button b = (Button) v.findViewById(R.id.button1);
b.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// CODE NEEDED HERER TO LOAD ACTIVITY / LAYOUT
break;
}
}
}
Any Help would be much appreciated thanks.
Just Use This..
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
setContentView(R.id.YOUR_LAYOUT_NAME)
break;
}
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), NewActivityname);
getActivity().startActivity(intent);
}
use this to work on button

Categories

Resources