Buttons in a fragment android - 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

Related

How to pass value to viewpager fragment from other activity?

Here let me explain my requirement i have two tabs of viewpager namely task and calls . There is one button in task fragment when user clicks that it will go to new activity from there users will enter the values in edittext then the values from this activity need to populate listview in task fragment of that viewpager how can i do this. So far what i have tried is:
THis is my Main activity:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// Bundle bundle=getIntent().getExtras();
// Intent intent=getIntent();
// ActivityView activityView=(ActivityView)intent.getSerializableExtra("yog");
// intent.putExtra("yogs",activityView);
// Bundle bundle=new Bundle();
// bundle.putSerializable("yogs",activityView);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String yogan = bundle.getString("yog");
String yogans = bundle.getString("yogs");
Bundle bundle1 = new Bundle();
bundle.putString("yoges", yogan);
bundle.putString("yogesh", yogans);
Task task = new Task();
task.setArguments(bundle1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
Task task=new Task();
return task;
case 1:
Calls calls=new Calls();
return calls;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Task";
case 1:
return "Call";
}
return null;
}
}
}
This is Task fragment in viewpager where listview is there:
package servicefiirst.precision.activitiestabs;
import android.content.Intent;
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.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class Task extends Fragment
{
List<ActivityView>activityViews;
ActivityView activityView=new ActivityView();
ActivityListAdapter activityListAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview= inflater.inflate(R.layout.yog,container,false);
ListView listview=(ListView)rootview.findViewById(R.id.listView);
if (activityViews == null)
{
activityViews = new ArrayList<ActivityView>();
}
if(getArguments()!=null) {
getArguments().getSerializable("yog");
}
activityViews.add(activityView);
activityListAdapter = new ActivityListAdapter(getActivity(), R.id.listView, activityViews);
listview.setAdapter(activityListAdapter);
activityListAdapter.notifyDataSetChanged();
Button btn=(Button)rootview.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), DetailActivity.class);
startActivity(intent);
}
});
return rootview;
}
}
This is detail activity where data go to populate listview in task fragment:
package servicefiirst.precision.activitiestabs;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class DetailActivity extends AppCompatActivity {
ActivityView activityView = new ActivityView();
// public static String endpoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText editText = (EditText) findViewById(R.id.editText);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.yog, R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
final Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityView.setDescription(editText.getText().toString());
activityView.setStatus(spinner.getSelectedItem().toString());
// Bundle bundle=new Bundle();
// bundle.putSerializable("yog", activityView);
Task task=new Task();
//task.setArguments(bundle);
android.support.v4.app. FragmentManager fm=getSupportFragmentManager();
android.support.v4.app. FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.container,task,"");
ft.commit();
}
});
}
}
how to navigate data from other activity to fragment of viewpager of other acitivity? can anybody help me
Please use static variable to save the value from your activity and then resuse it in task fragment by calling the task fragment of viewpager activity , i guess it would helps you..!!
Start the activity from task fragment using
startActivityForResult(Intent intent, int requestCode)
method, it will let fragment to receive result data from the activity. In new Activity when button is pressed to populate values save the values to a intent so you can send that intent to fragment by using
setResult(intent) // setResult has other overloaded methods pick them to your requirement
method of Activity class in your button onClickListener onClick() method.
Ex : onClick() {
intent.putString("name", editText.getText());
setResult(intent); // setting the intent as result to receive at fragment
this.finish(); // To finish the activity
}
When activity gets finished(when you call finish() or press back button)
onActivityResult(intent)
method of Fragment which started the activity will be automatically called. you can use this method to retrieve the intent which contained the populated data.

Pass ImageButton Value

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

How to create button dynamically from one activity to another activity

I am creating an android application that consists of adding button dynamically.Here when I click the button in one activity then a button will dynamically created another activity. Is it possible to create a button when clicking a button in one activity then create a button in another activity.Please help me with this.
package com.example.dynamicbutton;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button Add_Button;
Activity_2 act_child;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add_Button = (Button)findViewById(R.id.button_add);
Add_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent invisible = new Intent(MainActivity.this,Activity_2.class);
startActivity(invisible);
act_child.visible.setVisibility(View.GONE);
}
});
}
#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);
}
}
The solution is simple.Do Following in First Activity.
If the button clicked use following.
Intent invisible = new Intent(MainActivity.this,Activity_2.class);
//here add this line
.putExtra("visibility", "1");
startActivity(invisible);
else
Intent invisible = new Intent(MainActivity.this,Activity_2.class);
//here add this line
.putExtra("visibility", "0");
startActivity(invisible);
In your Second Activity:
String visibility = getIntent().getStringExtra("visibility");
if (visibility.equals("1")){
act_child.visible.setVisibility(View.VISIBLE);
}else{
act_child.visible.setVisibility(View.GONE);
}
Don't make variables public.Change your design to
1 ] Pass some variable to Second Activity . (In Button click of First Activity).
2 ] Get the variable in Second Activty & change the visibilty of Button (in Second Activity according to that variable)
Intent i = new Intent(CurrentActivity.this,SecondActivity.class);
i.putExtra("flag","show");
startActivity(i);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("flag");
if(value.equals("show")){
button1.setVisible(View.Visible);
}
else{
button1.setVisible(View.Gone);
}

addToBackStack() method is not working without overriding the onBackPressed() method in android

Here is the code of MainActivity which I have written.
I am loading the list of fragment in the first screen. When the user taps on any of the list items, the planet name will be shown to the user in the detail fragment which I have defined in a separate class.
I am adding the transaction of "Fragment Planet List" -> "Fragment Planet Detail" to back stack. So what I expect is when I press the back button from the fragment of planet detail, it should load planet list in the phone. But it is not happening this way.
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import com.meditab.fragments.fragment.FragmentPlanetDetail;
import com.meditab.fragments.fragment.FragmentPlanetList;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements Callback {
private FrameLayout frmPlanetList;
private FrameLayout frmPlanetDetail;
private boolean isPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frmPlanetList = (FrameLayout) findViewById(R.id.frmPlanetList);
frmPlanetDetail = (FrameLayout) findViewById(R.id.frmPlanetDetail);
if (null != frmPlanetDetail) {
isPhone = false;
} else {
isPhone = true;
}
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frmPlanetList, new FragmentPlanetList());
fragmentTransaction.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.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClicked(int intPosition) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
List<String> lstPlanetArray = getPlanetArray();
String strPlanetName = lstPlanetArray.get(intPosition);
FragmentPlanetDetail fragmentPlanetDetail = FragmentPlanetDetail.newInstance(strPlanetName);
if (isPhone) {
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.frmPlanetList, fragmentPlanetDetail);
} else {
fragmentTransaction.replace(R.id.frmPlanetDetail, fragmentPlanetDetail);
}
fragmentTransaction.commit();
}
private List<String> getPlanetArray() {
List<String> lstPlanets = new ArrayList<>(10);
lstPlanets.add("Mercury");
lstPlanets.add("Venus");
lstPlanets.add("Earth");
lstPlanets.add("Mars");
lstPlanets.add("Jupiter");
lstPlanets.add("Saturn");
lstPlanets.add("Uranus");
lstPlanets.add("Neptune");
lstPlanets.add("Saturn");
return lstPlanets;
}
}
However if I override the backPress method and pop the back stack programatically, it works just fine.
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Do I need to override the onBackPressed() method this way if I want to achieve this behavour?
It is not documented that you need to override this method in this link.Android Back Press Fragment Documentation
Fragment Planet Detail Class
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.meditab.fragments.R;
/**
* Created by BHARGAV on 25-Dec-14.
*/
public class FragmentPlanetDetail extends Fragment {
private String strPlanetName;
public FragmentPlanetDetail() {
}
public static FragmentPlanetDetail newInstance(String strPlanetName) {
FragmentPlanetDetail fragmentPlanetDetail = new FragmentPlanetDetail();
Bundle bundle = new Bundle();
bundle.putString("Planet_Name", strPlanetName);
fragmentPlanetDetail.setArguments(bundle);
return fragmentPlanetDetail;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (null != bundle) {
strPlanetName = bundle.getString("Planet_Name");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.planet_name, container, false);
TextView txtPlanetName = (TextView) rootView.findViewById(R.id.txtPlanetName);
txtPlanetName.setText(strPlanetName);
return rootView;
}
}
Fragment Planet List Class:
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.meditab.fragments.Callback;
import com.meditab.fragments.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by BHARGAV on 25-Dec-14.
*/
public class FragmentPlanetList extends Fragment {
private ListView listView;
private ArrayAdapter<String> stringArrayAdapter;
private Callback callback;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.listview, container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
stringArrayAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, getPlanetArray());
listView.setAdapter(stringArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
callback.onListItemClicked(position);
}
});
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback = (Callback) activity;
}
private List<String> getPlanetArray() {
List<String> lstPlanets = new ArrayList<>(5);
lstPlanets.add("Mercury");
lstPlanets.add("Venus");
lstPlanets.add("Earth");
lstPlanets.add("Mars");
lstPlanets.add("Jupiter");
lstPlanets.add("Saturn");
lstPlanets.add("Uranus");
lstPlanets.add("Neptune");
lstPlanets.add("Saturn");
return lstPlanets;
}
}
Callback Interface:
/**
* Created by BHARGAV on 26-Dec-14.
*/
public interface Callback {
public void onListItemClicked(int intPosition);
}
Thanks. Please let me know if any additional detail or code is needed.
Ok. So the reason why it is not working is the conflict of ActionBarActivty and Activity class differences.
And the differnce between getSupportFragmentManager() and getFragmentManager() methods of FragmentTransaction.
ActionBarActivity:
I was using ActionBarActivity which is android.support.v7.app.ActionBarActivity. This means I was using v7 compat library
FragmentManager:
Fragment Manager were not from the compat library. It was directly
import android.app.FragmentManager;
import android.app.FragmentTransaction;
as you can see in the MainActivity class.
Fragment:
android.app.Fragment; is the class which is imported in the separate fragment classes.
So once I changed from ActionBarActivity to Activity class, things were working fine.
The same holds true when I changed the FragmentManager,FragmentTransaction and Fragment classes to support library classes.
So after any of the modification, things started working normally.
Thanks.
Of course you don't need to override the onBackPressed() method. It's just a hack.
Your this condition is messing it up.
if (isPhone) {
fragmentTransaction.addToBackStack(null);
why don't you use this statement without condition once to see if it works. You can keep rest as it is. Just move this statement outside of the if condition.
Wierd, but I think
addToBackStack(null)
is the problem
Try replcing it with
addToBackStack("planetDetail");
You are using actionbar activity which extends fragment activity. Now, to have perfect behaviour, you need support fragments to work with actionbar activity.
Here you are using actionbar activity with normal fragments (not support v4 fragments) and that's what is causing the issue. So to have perfect behaviour, change your fragments to support fragments and it should work fine.
Let me know if that doesn't work.
Well I was having the same problem with you. What worked for me and I think its the solution for you too is to change the :
1.fragment with the fragment from the support library :
import android.support.v4.app.Fragment;
and
getFragmentManager() with the getSupportFragmentManager() :

Error on create a Button Listener

My intent is to get text from an EditText and view it in a Toast message. The code is this:
package com.example.primaapplicazione;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void fromEditToToast()
{
EditText e = (EditText)findViewById(R.id.editText1);
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
#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;
}
}
}
If I call the method "fromEditToToast()" in onCreate() without the "setOnClickListener()", it compiles properly and the app opens. If I call the same method with that function on the emulator app doesn't open, showing this message "Unfortunately, PrimaApplicazione has stopped.
What should I have to do?
I have seen this is a very common error, The PlaceholderFragment uses the fragment_main.xml that must contain the elements editText1 and button1, probably you have that elements defined in your activity_main.xml
It may be that views are not being instantiated while the activity has started. Device works faster than emulator so it might work in a device while not in emulator.
Implement your onClickListener directly in fragment and show the toast from there, it will work (assuming EditText and Button lies in fragment).
Try following code in your fragment and call the following function in your fragment's onViewCreated function to set the button's listener : -
private void set buttonOnClickListener()
{
EditText e = (EditText)getView().findViewById(R.id.editText1);
Button b = (Button)getView().findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//your code goes here;
}
});
}

Categories

Resources