I am developing an app in which first screen contains 4 different layouts with different images as background. What i want to do is if I click on one layout new fragment opens up with that background image on the top. Can i use same fragment to display different images and textviews ? if yes how ?
[not able to upload image due to less points ]
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
// Click methods goes here
public void clickAboutUs(View v)
{
/*Intent aboutUs = new Intent(MainActivity.this, FragmentAboutUs.class);
startActivity(aboutUs);*/
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragmentAboutUs = new FragmentAboutUs();
fragmentTransaction.add(R.id.container,fragmentAboutUs);
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);
}
}
FragmentAboutUs.java
public class FragmentAboutUs extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_us, container,false);
return view;
}
}
on clicking an layout i want fresh fragment screen with same image as background image of that particular background image which is stored in my drawables folder.
[1]: http://i.stack.imgur.com/PKX4L.png
Yes you can use same fragment for displaying different images and texts. You can add image resource id or path and the texts you want to display in arguments. Just initialise your fragment from main activity as below;
MyFragment myFragment = new myFragment();
Bundle bundle = new Bundle();
bundle.putInt("image",<image resourse id>);
bundle.putString("text1",<your string1>);
bundle.putString("text2",<your string2>);
myFragment.putArgs(bundle);
And inside your my fragment in ONcreate or ONcreateView get the data as below
Bundle bundle = getArguments();
imageId=bundle.getInt("image");
text1=bundle.getString("text1");
text2=bundle.getString("text2");
Hope this helps. Any doubt let me know.
Related
I am working on a project in which i am navigating from activity to a fragment which contains my reservation page with EditText fields like Name, Email Id. What i want to know is whether it is possible to get the values of those fields and send them as an email in fragment. if yes please help.
MainActivity.java
public class MainActivity extends AppCompatActivity {
FloatingActionButton fab;
RelativeLayout aboutUs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aboutUs = (RelativeLayout) findViewById(R.id.aboutUs);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//click methods goes here
public void clickAboutUs(View view){
/*android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
fragmentTransaction.replace(R.id.fragment_container, fragmentAboutUs);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
replaceFragment(fragmentAboutUs , true);
}
public void clickEvents(View view){
FragmentEvents fragmentEvents = new FragmentEvents();
replaceFragment(fragmentEvents,true);
}
public void clickMedia(View view){
FragmentMedia fragmentMedia = new FragmentMedia();
replaceFragment(fragmentMedia,true);
}
public void clickContact(View view){
FragmentContact fragmentContact = new FragmentContact();
replaceFragment(fragmentContact,true);
}
public boolean popFragment() {
boolean isPop = false;
Fragment currentFragment = getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStackImmediate();
}
return isPop;
}
#Override
public void onBackPressed() {
if (!popFragment()) {
finish();
}
}
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
#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);
}
}
Here is my fragment class
FragmentContact.java
public class FragmentContact extends Fragment
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contac_us, container,false);
return view;
}
}
In fragment FragmentContact i am planning to include reseration form. I search for "Registration page using fragment in android" but didnt get any help.
There is nothing different about the code that goes in a Fragment vs an Activity. You can use findViewById just like you have been, but you simply need to use the inflated view.
public class FragmentContact extends Fragment
{
private EditText address, body;
private Button sendEmailButton;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contac_us, container,false);
sendEmailButton = (Button) view.findViewById(R.id.send_email);
sendEmailButton.setOnClickListener(...); // TODO: Implement
return view;
}
public void sendEmail(String address, String body) { }
}
How can I ensure that a button inside a list item is clickable, because I am trying to make the button clickable so that it can transition to a different fragment?
Like the listview and the list items inside it are part of a fragment and I want to ensure that clicking a specific button inside a list item will transition to the new fragment.
MainActivity Code:
It contains tabs(not all of which are implemented yet, but thats not an issue right now)
public class MainActivity extends FragmentActivity implements HomeFragment.OnFragmentInteractionListener {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the tabs which hold different fragments, it will currently crash because of the null
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this,getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("Home"), HomeFragment.class , null);
// mTabHost.addTab(mTabHost.newTabSpec("search").setIndicator("Search"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("post").setIndicator("Post"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("books").setIndicator("Books"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("me").setIndicator("Me"),null/*fragment here*/,null);
}
#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);
}
//For home fragment...parameter might change
#Override
public void onFragmentInteraction(String id) {
Button viewPostings = (Button) findViewById(R.id.view_postings);
viewPostings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PostDetailFragment fragment = PostDetailFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, fragment).addToBackStack(null).commit();
}
});
}
}
Im trying to launch the new activity from the implementation of onFragmentInteractionListener. The app loads the list view and its contents, but the individual buttons in it aren't clickable.
First off you need to add this line to make the items in the custom list item clickable:
android:descendantFocusability="blocksDescendants"
Add this property to the enclosing layout.
Secondly, you need to set the onClickListener in the getView method of the custom adapter that you have made for your custom ListView. For example, that would be something like this:
ImageButton deleteBtn = (ImageButton) view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code here
}
});
Use some sort of ListAdapter such as an ArrayAdapter to populate your ListView. That way, you can use the adapter to handle the button clicks.
In your list fragment, use the onItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(foodList.get(position));
}
}
Then in your parent activity, you will have something like this.
#Override
public void onFragmentInteraction(Food food) {
//going from ListFragment to DetailFragment
//call detail fragment here
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment fragment = DetailFragment.newInstance(food);
ft.replace(R.id.container, fragment);
ft.addToBackStack( "tag" );
ft.commit();
}
I would like to know if anyone knows a way to achieve both forward and backward navigation with Fragments?
I would like to start with a single Fragment, when I press the next button a new Fragment must be created, when I push the back button, the previous Fragment must be shown. My code does this and it saves any changes I have made to any previous Fragments as they are saved in the back stack, however, I want the same to be true of forward navigation, is there any way in which I can achieve this?
So to be more exact, I want to for example create 10 Fragments all with a single text box in which I can enter some data, each time I enter data and press the next button it must navigate to the next Fragment, have an empty text box and save the previous Fragment plus data entered to the back stack (this it currently does). So when I get to Fragment 10, I want to be able to go back to Fragment 1 and then back to Fragment 10 but as I navigate forward again, the data I originally entered must still be there. Then when I navigate to Fragment 11 it must be an empty text box. So it must be a forward and backward navigation system of sorts.
The code below generates Fragments dynamically from code and adds Views to it dynamically as well (at run time). This is the code I currently have working for going backwards.
public class MainActivity extends Activity
{
int mStackLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button IntegratedBiometricsButton = (Button) findViewById(R.id.integrated_biometrics_button);
IntegratedBiometricsButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent IBIntent = new Intent(MainActivity.this, SimpleScanActivity.class);
startActivity(IBIntent);
}
});
// Watch for button clicks.
Button button = (Button) findViewById(R.id.new_fragment);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
addFragmentToStack();
}
});
button = (Button) findViewById(R.id.delete_fragment);
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
getFragmentManager().popBackStack();
if(mStackLevel > 0){mStackLevel--;}
}
});
if (savedInstanceState == null)
{
// Do first time initialization -- add initial fragment.
Fragment newFragment = CountingFragment.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else
{
mStackLevel = savedInstanceState.getInt("level");
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
#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);
}
void addFragmentToStack()
{
mStackLevel++;
// Instantiate a new fragment.
Fragment newFragment = CountingFragment.newInstance(mStackLevel);
// Add the fragment to the activity, pushing this transaction
// on to the back stack.
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
public static class CountingFragment extends Fragment
{
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
static CountingFragment newInstance(int num)
{
CountingFragment f = new CountingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
int ID = 0;
View v = inflater.inflate(R.layout.fragment_layout, container, false);
LinearLayout fragmentLayout = (LinearLayout) v.findViewById(R.id.infoLayout);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(container.getContext());
tv.setId(ID);
ID++;
tv.setTextSize(16);
tv.setText("Fragment #" + mNum);
tv.setGravity(Gravity.CENTER);
tv.setLayoutParams(lp);
fragmentLayout.addView(tv);
EditText et = new EditText(container.getContext());
et.setId(ID);
ID++;
et.setHint("Text");
et.setGravity(Gravity.CENTER);
et.setInputType(InputType.TYPE_CLASS_NUMBER);
et.setLayoutParams(lp);
fragmentLayout.addView(et);
CheckBox cb = new CheckBox(container.getContext());
cb.setId(ID);
cb.setChecked(false);
cb.setGravity(Gravity.LEFT);
cb.setLayoutParams(lp);
fragmentLayout.addView(cb);
cb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(((CheckBox) v).isChecked())
{
Toast.makeText(v.getContext(), "Yo", Toast.LENGTH_LONG).show();
}
}
});
ID++;
ImageView iv = new ImageView(container.getContext());
iv.setId(ID);
iv.setImageResource(R.drawable.output);
iv.setLayoutParams(lp);
fragmentLayout.addView(iv);
iv.setOnLongClickListener(new View.OnLongClickListener()
{
public boolean onLongClick(View v)
{
Toast.makeText(v.getContext(), "It works", Toast.LENGTH_LONG).show();
return true;
}
});
ID++;
//View tv = v.findViewById(R.id.text);
//((TextView) tv).setText("Fragment #" + mNum);
//tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
}
}
I have a problem with adding the fragment transactions to the back stack. I have a Main activity in which I populate my layout with a Menu Fragment:
public class MainActivity extends ActionBarActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().add(R.id.frag_container, new MainMenuFragment()).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);
}
}
Then, inside the MainMenuFragment, the user chooses some option which results in replacing the menu fragment with some other fragment:
public class MainMenuFragment extends Fragment implements OnItemClickListener{
GridView grid;
FragmentManager manager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.main_menu_fragment, container, false);
manager = getActivity().getFragmentManager();
grid = (GridView) root.findViewById(R.id.gridView1);
grid.setAdapter(new MenuTileAdapter(getActivity()));
grid.setOnItemClickListener(this);
return root;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTransaction trans = manager.beginTransaction();
if (position == 0){
trans.replace(R.id.frag_container, new BasicSettingsFragment());
trans.addToBackStack(null);
trans.commit();
}
}
}
For what i understand, this should make it so that when the user presses back button on their device, they will be brought back to the menu fragment, but instead this quits the app. What am i doing wrong?
In your Activity overwrite:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
And probably you need to use in every commited fragment transaction:
FragmentTransaction.addToBackStack(null);
Your code is a mixup, you use ActionBarActivity from appcompat and not using getSupportFragmentManager() and the fragments import should be the appcompat one if you decide to use it. If not, use Activity instead of ActionBarActivity and the simple Fragment import with FragmentManager
Add this to your activity android:configChanges="keyboardHidden|orientation|screenSize"
This will stop your activity from restarting when you rotate.
use setRetainInstance(true) on fragments.
You are not adding the MainMenuFragment to the back stack. You can try this one on your activity:
getFragmentManager().beginTransaction().add(
R.id.frag_container, new MainMenuFragment()).
addToBackStack(null).commit();
When you add or replace a fragment with the FragmentManager, you need to manually add the old fragment to the backstack with addToBackStack() before calling commit().
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a very simple android app being built. I have 2 buttons and 1 textview. I build them graphically in fragment_main.xml. Below is my full codes.
public class MainActivity extends ActionBarActivity {
TextView tvOut;
Button btnOk;
Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
}
#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 comment this part of the codes it works well.
View.OnClickListener oclBtnOk = new View.OnClickListener() {
public void onClick(View v) {
// change text of the TextView (tvOut)
tvOut.setText("Button OK clicked");
}
};
btnOk.setOnClickListener(oclBtnOk);
Even though I use setContentView(R.layout.main_activity); all my button and text view appears and quite puzzle why even with main_activity my buttons and text view appears well.
You never assign values to your views. Use findViewById to get references to the views with the id's you gave them in your XML layout.
setContentView(R.layout.fragment_main);
// get the views
btnOk = (BUtton) findViewById(R.id.your_button_id);
tvOut = (TextView) findViewById(R.id.another_id);
btnOk.setOnClickListener(...);