Fragments: how to change content? - java

I have a class that manages a fragment .. in a TextView I have to put the phone features, but because by mistake?
import android.os.Build;
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 PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page, null);
return view;
}
String model = Build.MODEL;
String product = Build.PRODUCT;
String androidOS = Build.VERSION.RELEASE;
String scheda = model+"\n"+androidOS+" \n "+product+"";
TextView text = (TextView) findViewById(R.id.textView3);
text.setText(scheda);
private TextView findViewById(int textview3) {
// TODO Auto-generated method stub
return null;
}
}
I did not understand a thing. I have three fragment, one of which is called Home, one faq and one about. How do I change the contents of the various "screens"?

Firstly you cannot have operations on objects in the main class body without a helper method in java. I also see when you are creating a reference to you TextView, you need to find the TextView from your inflated view, so the right way to do it would be something like
TextView text = (TextView)view.findViewById(R.id.textview3);
Lastly, when inflating the view, pass the ViewGroup as the parent for that view, and a false for the attachToRoot
You should have something like:
public class PageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_page,container,false);
String model = Build.MODEL;
String product = Build.PRODUCT;
String androidOS = Build.VERSION.RELEASE;
String scheda = model+"\n"+androidOS+" \n "+product+"";
TextView text = (TextView) view.findViewById(R.id.textView3);
text.setText(scheda);
return view;
}
}
Hope that helps

Related

null point exception when trying to fetch data from openweathermap [duplicate]

This question already has answers here:
getView returning null when fragment has been created from an activity
(6 answers)
Closed 5 years ago.
I am trying to get sunrise and sunset time for my current location from openweathermap api. I am following this tutorial.
I have copied the entire Function.java in the tutorial and trying to use the data to update my ViewPagerAdapter's Fragment.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
TextView cityField = getView().findViewById(R.id.tv_city);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
}
});
asyncTask.execute("25.180000", "89.530000"); // asyncTask.execute("Latitude", "Longitude")
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"Hello", "World"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
and I have named my target for the city name as tv_city:
<TextView
android:id="#+id/tv_city"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="40sp"
android:text="Hello World"
android:textSize="30sp"
android:layout_marginBottom="5sp"
android:paddingLeft="5sp"
android:gravity="top" >
</TextView>
The problem is, possibly I am making some mistake to fetch the data, as I am getting nul exception error for this line:
TextView cityField = getView().findViewById(R.id.tv_city);
as:
Process: com.example.phocast, PID: 9820 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.phocast.BlankFragment.<init>(BlankFragment.java:17)
WIth my limited knowledge in java, I am unable to solve it.
Kindly help.
Update
actually, writing oncreateview as:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
rv.setNestedScrollingEnabled(true);
Weather_OWM.placeIdTask asyncTask =new Weather_OWM.placeIdTask(new Weather_OWM.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
TextView cityField = rootView.findViewById(R.id.tv_city);
cityField.setText(weather_city);
}
});
solves my problem, but i dont know if this is proper/good way to use final. I will be really grateful if someone shows me the way before closing it.
Your cityView line of code is just hanging out there, not in a method or anything. The NullPointer is coming from getView(). You can't find the view before onCreateView occurs and the inflater does its thing. Move it to onCreateView, anytime after View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
You need initialize the textView after:
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
After initialize the recyclerView you can write this:
cityField = rootView.findViewById(R.id.tv_city);

Displaying CardViews inside a RecyclerView using FirebaseUI and Firebase database

I am trying to display CardViews inside a RecyclerView, each card will represent a cheese object.
This cheese object has 6 instance variables.
This is my Cheese.java :
public class Cheese {
private String CheeseName;
private String CheeseCountryOfOrigin;
private String CheeseDayMade;
private String CheeseDayExpire;
private String CheeseDescription ;
private String CheesePrice;
public Cheese(){} //Required for firebase
public Cheese(String CheeseName, String CheeseCountryOfOrigin, String CheeseDayMade, String CheeseDayExpire, String CheeseDescription, String CheesePrice) {
this.CheeseName = CheeseName;
this.CheeseCountryOfOrigin = CheeseCountryOfOrigin;
this.CheeseDayMade = CheeseDayMade;
this.CheeseDayExpire = CheeseDayExpire;
this.CheeseDescription = CheeseDescription;
this.CheesePrice = CheesePrice;
}
public String getCheeseName() {
return CheeseName;
}
public String getCheeseCountryOfOrigin() {
return CheeseCountryOfOrigin;
}
public String getCheeseDayMade() {
return CheeseDayMade;
}
public String getCheeseDayExpire() {
return CheeseDayExpire;
}
public String getCheeseDescription() {
return CheeseDescription;
}
public String getCheesePrice() {
return CheesePrice;
}
}
and this is my cheese_card.xml (I hardcoded some android:text for better understanding): cheese_card.xml
my RecyclerView is in a fragment.
This is my fragment:
fragment_cheeses_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cheeses_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
all my cheese items are already in my Firebase Real-Time Database. To make my life simpler I am trying to use FirebaseUI to populate my RecyclerView with data from my Firebase database.
This is my CheesesListFragment.java, which is displayed in my MainActivity:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class CheeseListFragment extends Fragment {
private static final String TAG = "CheesesListFragment";
private FirebaseDatabase aFirebaseDatabase;
private DatabaseReference aCheesesDatabaseReference;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e(TAG, "onCreateView Started Successfully");
//Create the recycler view object
RecyclerView cheesesRecycler = (RecyclerView) inflater.inflate(R.layout.fragment_cheeses_list, container, false);
//Add a grid layout manager to the recycler view
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
cheesesRecycler.setLayoutManager(layoutManager);
cheesesRecycler.setHasFixedSize(true);
aFirebaseDatabase = FirebaseDatabase.getInstance();
aCheesesDatabaseReference = aFirebaseDatabase.getReference().child("cheeses");
//Query the cheeses in firebase db using firebaseUI instead of addChildEventListener
Query query = aCheesesDatabaseReference;
//configuration for the FirebaseRecyclerAdapter
FirebaseRecyclerOptions<Cheese> options =
new FirebaseRecyclerOptions.Builder<Cheese>()
.setQuery(query, Cheese.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Cheese, CheeseViewHolder>(options) {
#Override
public CheeseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.cheese_card for each item
CardView cv = (CardView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.cheese_card, parent, false);
return new CheeseViewHolder(cv);
}
#Override
protected void onBindViewHolder(CheeseViewHolder holder, int position, Cheese model) {
CheeseViewHolder myHolder = (CheeseViewHolder)holder;
myHolder.cheeseName.setText(model.getCheeseName());
myHolder.cheeseCountryOfOrigin.setText(model.getCheeseCountryOfOrigin());
myHolder.cheeseDayMade.setText(model.getCheeseDayMade());
myHolder.cheeseDayExpire.setText(model.getCheeseDayExpire());
myHolder.cheeseDescription.setText(model.getCheeseDescription());
myHolder.cheesePrice.setText(model.getCheesePrice());
}
};
//Set the adapter to the recycle View
cheesesRecycler.setAdapter(adapter);
return cheesesRecycler;
}
public static class CheeseViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView CheeseName;
TextView CheeseCountryOfOrigin;
TextView CheeseDayMade;
TextView CheeseDayExpire;
TextView CheeseDescription;
TextView CheesePrice;
public CheeseViewHolder (CardView v){
super(v);
cardView = v;
CheeseName = (TextView)cardView.findViewById(R.id.cheese_name);
CheeseCountryOfOrigin= (TextView)cardView.findViewById(R.id.cheese_origin);
CheeseDayMade= (TextView)cardView.findViewById(R.id.cheese_day_made);
CheeseDayExpire= (TextView)cardView.findViewById(R.id.cheese_day_expire);
CheeseDescription= (TextView)cardView.findViewById(R.id.cheese_description);
CheesePrice= (TextView)cardView.findViewById(R.id.cheese_price);
}
}
}
So my questions are: (answering any of them is welcomed and very helpful)
If i get it right, onCreateViewHolder is supposed to make ViewHolders for my Cheese object using my cheese_card.xml . if so, assuming I delete onBindingViewHolder am I suppose to see lots of view holders that look like my cheese_card.xml?
in onBindingViewHolder in setText : how can I get my TextViews to get a value from my firebase?
I am new to programming and not sure about onCreateViewHolder, onBindingHolder and cheesesViewHolder.I am not sure what every code I writed there means as some of them are copy-pasted.If I got it all wrong, can you please explain how can I reach my desired outcome, and what I did wrong?
Thank you, in advance :)
Modify onBindingViewHolder and cheesesViewHolder. Because in onBindingViewHolder you will bind data with Views not Views with they ids. Bind Views with they ids inside cheesesViewHolder. For example:
CardView cardView;
TextView cheese_name;
TextView cheese_origin;
public CheeseViewHolder(CardView v) {
super(v);
cardView = v;
cheese_name = (TextView) cardView.findViewById(R.id.cheese_name);
cheese_origin = (TextView) cardView.findViewById(R.id.cheese_origin);
// and so on...
}
Then inside onBindingViewHolder you will do something like this:
#Override
protected void onBindViewHolder(CheeseViewHolder holder, int position, Cheese model) {
cheesesViewHolder myHolder = (cheesesViewHolder)holder;
myHolder.cheese_name.setText(model.getCheeseName());
myHolder. cheese_origin.setText(model.getCheeseOrigin());
//and so on...
}
I was able to eventually fix my problem and get onCreateViewHolder and onBindViewHolder to start simply by adding
adapter.startListening();
to my onStart method. like this:
#Override
public void onStart() {
super.onStart();
Log.e(TAG,"onStart Started Successfully");
adapter.startListening();
}
And I edited the code using #Yupi suggestion.

Unable to pass intent in custom array adapter

I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary

Rating Bar Android

Hi I am busy making a program where you get to rate people
I've been playing around with the Rating Bar widget however I am struggling to make it show a rating after selecting the amount of stars. What I'm I doing wrong. I would also like to to know if the android sdk have anything on up and down votes and would it be wise to use images for a rating system.
The reason why some of the code is commented out is because my app won't run when its uncommented but I know its needed to do what I want to do.
import android.app.Activity;
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.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
public class rating_system_fragment extends Fragment implements OnRatingBarChangeListener{
RatingBar ratingBar;
TextView ratingResult;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater.inflate(R.layout.rating_system_fragment,container,false);
//setContentView(R.layout.activity_main);
return inflater.inflate(R.layout.rating_system_fragment, container, false);
//ratingResult = (TextView) ratingResult.findViewById(R.id.textViewRating);
//((RatingBar) ratingBar.findViewById(R.id.ratingBar))
// .setOnRatingBarChangeListener(this);
}
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
ratingResult.setText(rating + "/" + numStars);
}
}
You have several syntax erros in your commented code. It should look like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.rating_system_fragment,container,false);
ratingResult = (TextView) rootView.findViewById(R.id.textViewRating);
ratingBar = (RatingBar) rootView.findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(this);
return rootView;
}
The key here is that ratingBar and textViewRating are childs of your root view, and should only be accessed when you have aready inflated them.

Fragment and view

My application is divided into fragments, each with its own layout (.xml file).
When I start visualize the first fragment in the onCreate() method of my activity, I set the appropriate layout with setContentView(fragment_first). How do I change, for example, a TextView contained inside the second fragment (fragment_second)?
Generally speaking, a Fragment, or any Activity or View for that matter, should update its own internal UI controls. It's easier, and it's good design. Other classes/events may update the state of the Fragment's data, but it handles how that state is displayed.
Edit to answer commented question:
This is how to load a content view in a Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.pump_info, container, false);
return view;
}
in your onCreateView() method, you should assign all of the views you will need to access later to fields in your fragment class, like this,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
view = inflater.inflate(R.layout.xxx, container, false);
this.aTextView = (TextView)view.findViewById(R.id.a_text_view);
this.anImageView = (ImageView)view.findViewById(R.id.an_image_view);
...
}
you can then use aTextView, etc. at other places in the execution of your fragment.
It seems you set the xml file you intended for your first fragment in your activity.
What you should do in short is create a completely new class and have it extend android.support.v4.app.Fragment, also have your activity extend FragmentActivity instead of just Activity.
Then in your android.support.v4.app.Fragment class (which I shall call your fragment from now on) you should override the onCreateView(LayoutInflater inflate, ViewGroup container, Bundle savedInstanceState){} method and in this method you should put a line like this:
View view = inflater.inflate(R.layout.the_xml_layout_for_this_fragment, container, false); which inflates the layout of the fragment and plants it in the proper place in your activity's layout.
After this your need to return view;, but before you return this view you can do view.findViewById(R.id.id_of_a_view_from_the_xml_layout_file); in order to find an element and manipulate it.
You should create such a fragment class for each fragment you need in your app and have it inflate it's own xml layout file.
For more detailed instructions you can see http://www.youtube.com/watch?v=4BKlST82Dtg or other videos or written tutorials.
EDIT: here is a basic fragment class:
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 MyFrag extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate the view:
View view = inflater.inflate(R.layout.myfrag_layout, container, false);
// manipulate widgets, for example:
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("read me!!!");
// return the view:
return view;
}
}
and it's parenting activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class MyFragmentActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// notice that there is a different layout file for the activity and for
// the fragment!
setContentView(R.layout.xml_layout_for_the_activity);
// to start the fragment and stick it into your activity (not needed if
// you use ViewPager)
FragmentManager fragMan = getSupportFragmentManager();
fragMan.beginTransaction()
.add(R.id.the_visual_element_that_will_contain_your_fragments_layout, fragMan)
.commit();
}
}

Categories