I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.
Related
I'm a beginner who learning Android basic course
I want to make 6 fragments that have same structure (only title, image, texts will be different) by using single fragment.
I tried this code but I can see only one fragment.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.fragment_container);
MoviePagerAdapter adapter = new MoviePagerAdapter(getSupportFragmentManager());
mainfragment = new MainFragment();
adapter.addItem(mainfragment);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(6);
}
ViewPager Adapter (in MainActivity)
class MoviePagerAdapter extends FragmentStatePagerAdapter {
public ArrayList<Fragment> items = new ArrayList<Fragment>();
#Override
public Fragment getItem(int position) {
return items.get(position);
}
public MoviePagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
public void addItem(Fragment item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
}
MainFragment.java
public class MainFragment extends androidx.fragment.app.Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment, container,
false);
//...
'i want to make 6fragments with datas below '
movieData = new MovieData("title1", "rate1", "grade1");
addData(movieData);
movieData = new MovieData("title2", "rate2", "grade2");
addData(movieData);
movieData = new MovieData("title3", "rate3", "grade3");
addData(movieData);
movieData = new MovieData("title4", "rate4", "grade4");
addData(movieData);
movieData = new MovieData("title5", "rate5", "grade5");
addData(movieData);
movieData = new MovieData("title6", "rate6", "grade6");
addData(movieData);
return rootView;
}
public void addData(MovieData movieData){
Bundle bundle = new Bundle();
bundle.putParcelable("data", movieData);
MainFragment mainFragment = new MainFragment();
mainFragment.setArguments(bundle);
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
change your code like this:
public class MainActivity extends AppCompatActivity {
private MoviePagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.fragment_container);
adapter = new MoviePagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(6);
for(int i =0;i<6;i++){
createFrag(i);
}
}
}
private void createFrag(int number) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putInt("NUMBER",number);
fragment.setArguments(args);
adapter.addItem(fragment);
adapter.notifyDataSetChanged();
}
class MoviePagerAdapter extends FragmentStatePagerAdapter {
public ArrayList<Fragment> items = new ArrayList<Fragment>();
#Override
public Fragment getItem(int position) {
return items.get(position);
}
public MoviePagerAdapter(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
public void addItem(Fragment item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
}
and change your Fragment like this:
public class MainFragment extends androidx.fragment.app.Fragment {
//1st
private int number;
#Nullable
//this is variant 1 - with static Movie data
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment,
container,
false);
//...
//2d
assert getArguments() != null;
number = getArguments().getInt("NUMBER");
switch (number) {
case 0:
MmovieData movieData1 = new MovieData("title1", "rate1",
"grade1");
addData(movieData1);
break;
case 1:
MmovieData movieData2 = new MovieData("title2", "rate2",
"grade2");
addData(movieData2);
break;
//...
}
return rootView;
}
public void addData(MovieData movieData){
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
and this is variant 2 ( with dynamic data and listener)
public class MainFragment extends androidx.fragment.app.Fragment {
//1st
private int number;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment,
container,
false);
//...
//2d
assert getArguments() != null;
number = getArguments().getInt("NUMBER");
return rootView;
}
//some method of listener changed
public void dataChanged(MovieData movieData, int position){
if(number==position){
title.setText(movieData.title);
reservation_rate.setText(movieData.getReservation_rate());
grade.setText(movieData.getGrade());
image.setImageResource(R.drawable.image6);
}
}
I have 3 fragments that are generated from the same class file. These three fragments exist within a ViewPager and a FragmentStatePagerAdapter.
They are in sliding tabs. They are created once and never dismissed or deleted or go out of memory.
The app works fine so far, but I need to figure out how to make the fragments have knowledge of their own index (1,2, or 3).
Is there some code like:
int myIndex = summonTheAllKnowingThing.getWhatFragmentThisIsPlease();
That I can add somewhere in the following code?
public class BlankFragment extends Fragment implements View.OnClickListener {
private boolean isDone = false;
EditText persons_name;
Spinner disc1_spinner;
Spinner disc2_spinner;
Spinner disc3_spinner;
Spinner fee1_spinner;
Spinner fee2_spinner;
EditText custom_disc;
EditText custom_fee;
Button doneButton;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance() {
BlankFragment fragment = new BlankFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// getView().findViewById(R.id.
persons_name = (EditText) getView().findViewById(R.id.NAME);
disc1_spinner = (Spinner) getView().findViewById(R.id.DISC1);
disc2_spinner = (Spinner) getView().findViewById(R.id.DISC2);
disc3_spinner = (Spinner) getView().findViewById(R.id.DISC3);
custom_disc = (EditText) getView().findViewById(R.id.customDISC);
custom_fee = (EditText) getView().findViewById(R.id.customFEE);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.doneButton:
if MainActivity.is1Done
doneButton.setBackgroundColor(Color.RED);
MainActivity.name1 = persons_name.getText().toString();
break;
}
}
}
Best approach is to pass the index while creating the fragment in pager adapter as in
#Override
public Fragment getItem(int position) {
return BlankFragment.newInstance(position);
}
and BlankFragment would be
public class BlankFragment extends Fragment implements View.OnClickListener {
private int myIndex; //<-- access it for getting its index
//.. some other variables
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(int indexInPager) {
BlankFragment fragment = new BlankFragment();
Bundle bundle = new Bundle();
bundle.putInt("index",indexInPager);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myIndex = getArguments().getInt("index");
View v = inflater.inflate(R.layout.fragment_blank, container, false);
doneButton = (Button) v.findViewById(R.id.doneButton);
doneButton.setOnClickListener(this);
return v;
}
//.. some other code
}
This question is something serious for me , i need to someone help me regarding this. Actually i am creating an RSS feed app by combining navigation drawer and view pager tabbed activity. i want to pass a string value from one fragment to other fragment. here is the thing. It was working properly when it was with the navigation drawer activity but after combining with view-pager , String is not passing to other fragment through bundle, i can't find the error because its not showing any error,
This is from i am passing string
public class RssFragment extends Fragment implements OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
startService();
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService.class);
getActivity().startService(intent);
}
/**
* Once the {#link RssService} finishes its task, the result is sent to this BroadcastReceiver
*/
private BroadcastReceiver resultReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
List<RssItem> items = (List<RssItem>) intent.getSerializableExtra(RssService.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getDescription());
String string;
string=uri.toString();
result Des_1=new result();
FragmentManager fragmentManager1 =getActivity().getSupportFragmentManager();
fragmentManager1.beginTransaction().replace(R.id.content_main_layout_frame,Des_1 ).addToBackStack("fragBack").commit();
result ldf = new result();
Bundle args = new Bundle();
args.putString("YourKey", string);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_main_layout_frame, ldf).commit();
}
#Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter(RssService.ACTION_RSS_PARSED);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(resultReceiver, intentFilter);
}
#Override
public void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(resultReceiver);
}
}
This is how i am receiving the string
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
Bundle bundle = getArguments();
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(bundle != null) {
String value = bundle.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I pleasing someone to figure it out. i repeat it was working but now its not
It is another fragment
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new RssFragment();
break;
case 1:
fragment = new RssFragment();
break;
case 2:
fragment = new RssFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
Try the below one,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.replace(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Remove both the transaction and add the below code instead,
ldf = new result();
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager().beginTransaction();
bundle.putString("key","value");
ldf.setArguments(bundle);
fragmentTransaction.addToBackStack("fragBack");
fragmentTransaction.add(R.id.content_main_layout_frame, ldf);
fragmentTransaction.commit();
Let me know if that helps!
Try this
public class result extends Fragment {
public result() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_result,container,false);
TextView textView=(TextView)rootview.findViewById(R.id.distext);
if(savedInstanceState!= null) {
String value = savedInstanceState.getString("YourKey");
textView.setText(value);
// Toast.makeText(getActivity(), value,
// Toast.LENGTH_LONG).show();
}
return rootview;
}
}
I am having a problem with fragments. I want to start a fragment when I click an item from a Contacts list and then, when I press the phone back button I wanna go back to the contacts list. The fragments starts, but when I press the back button it doesn't go to the contacts lists, it just exists the application and gets to the phone menu.
This is for the contacts list
public class ChatMainActivity extends FragmentActivity{
private static Button btnLogOut;
private static SessionManager sm;
private static ListView listView ;
private List<ContactData> contactsList;
private static class ContactListFragment extends Fragment
{
public static Fragment newInstance(){
ContactListFragment ourList = new ContactListFragment();
return ourList;
}
#Override
public View onCreateView(LayoutInflater inflater,final ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactlistfragment,container,true);
listView = (ListView) v.findViewById(R.id.listView);
btnLogOut = (Button) v.findViewById(R.id.btnLogOut);
btnLogOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SessionManager sm = new SessionManager(v.getContext());
sm.logoutUser();
Intent i = new Intent(v.getContext(),MainActivity.class);
startActivity(i);
getActivity().finish();
}
});
System.out.println("fetch" + sm.fetchContacts());
List<String> nume = new ArrayList<String>();
List<ContactData> contactsList = new ArrayList<ContactData>();
for(String contact : SessionManager.getUserObj().getContactsInfo())
{
for(int i=0; i< sm.fetchContacts().size(); i=i+2){
if(sm.fetchContacts().get(i+1).equals(contact)){
contactsList.add(new ContactData(sm.fetchContacts().get(i).toString(),sm.fetchContacts().get(i+1).toString(),true));
nume.add(sm.fetchContacts().get(i));
}
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, nume);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
// String itemValue = (String) listView.getItemAtPosition(position);
MessagingFragment cChat = new MessagingFragment();
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
System.out.println("Removed Views? ");
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer,cChat).commit();
// Intent i = new Intent(view.getContext(), MessagingActivity.class);
// startActivity(i);
// Here is the tricky part
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Here we set our custom adapter. Now we have the reference to the activity
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_main_layout);
sm = new SessionManager(this);
if (SessionManager.getUserObj() == null){
// We are checking to see if the Singleton object is set, if it isn't we must send the user back to login screen.
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
ContactListFragment clist = new ContactListFragment();
getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer, clist).commit();
}
}
and this is the fragment
public class MessagingFragment extends Fragment {
private EditText et ;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
container.removeAllViews();
container.removeAllViewsInLayout();
View v = inflater.inflate(R.layout.messaging_screen,null,true);
et = (EditText) v.findViewById(R.id.etmessage);
v.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init1");
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
et = (EditText) view.findViewById(R.id.etmessage);
view.findViewById(R.id.sendMessageButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateMessageHistory(et.getText().toString());
et.setText("");
}
});
System.out.println("Init2");
}
public void updateMessageHistory(String newText){
TextView tv = (TextView) getView().findViewById(R.id.messageHistory);
String oldText = tv.getText().toString();
oldText = oldText + "\n" + newText ;
tv.setText(oldText);
}
}
Any help would be appreciated.
Back stack is not turned on for fragments by default. But you can enable it easily. Try in your Activity's onCreate() to replace:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.commit();
with
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, clist)
.addToBackStack(null)
.commit();
More info on Back stack:
http://android-er.blogspot.com/2013/04/allow-navigate-back-through.html
In my application I want to put a ListView in the first Fragment and I want to move to a new Fragment when I clicked on an item such that each item has its own details
in my code.
I implemented it to move to another Activity, but now my manager says it must go to another Fragment instead of other activity. I'm new to the Fragment world and I don't know how to do this. The manager says that I can use the list fragment but I have not found any useful code.
This my code:
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
static ProgressDialog pd ;
ViewPager mViewPager;
List<Fragment> fragments ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFour.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFive.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentSix.class.getName()));
mSectionsPagerAdapter=new SectionsPagerAdapter(super.getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
pd = new ProgressDialog(this);
mViewPager.setAdapter(mSectionsPagerAdapter);
//
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % 6;
return fragments.get(_pos);
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#Override
public CharSequence getPageTitle(int position) {
final String title_section4="Section4";
final String title_section5="Section5";
final String title_section6="Section6";
final String title_section1="Section1";
final String title_section2="Section2";
final String title_section3="Section3";
Locale l = Locale.getDefault();
switch (position) {
case 0:
return title_section1.toUpperCase(l);
case 1:
return title_section2.toUpperCase(l);
case 2:
return title_section3.toUpperCase(l);
case 3:
return title_section4.toUpperCase(l);
case 4:
return title_section5.toUpperCase(l);
case 5:
return title_section6.toUpperCase(l);
}
return null;
}
}
public static class FragmentOne extends Fragment {
ArrayList< String > ar;
ArrayAdapter< String > ad ;
ListView lv ;
TextView tv;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.one, container, false);
tv = (TextView) rootView.findViewById(R.id.mywidget);
tv.setSelected(true);
ar = new ArrayList<String>();
lv = (ListView) rootView.findViewById(R.id.listView1);
for (int i = 0 ; i< 10 ; i++){
ar.add("My Item " + String.valueOf(i));
}
ad = new ArrayAdapter<String>
(getActivity().getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
ar);
lv.setAdapter(ad);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast t = Toast.makeText(getActivity(), "Message",
Toast.LENGTH_SHORT);
t.show();
Intent i = new Intent(getActivity(), tst.class);
startActivity(i);
}
});
return rootView;
}
}
public static class FragmentTwo extends Fragment {
public FragmentTwo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.two, container, false);
return rootView;
}
}
public static class FragmentThree extends Fragment {
public FragmentThree() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.three, container, false);
return rootView;
}
}
public static class FragmentFour extends Fragment {
public FragmentFour() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.four, container, false);
return rootView;
}
}
public static class FragmentFive extends Fragment {
public FragmentFive() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.five, container, false);
return rootView;
}
}
public static class FragmentSix extends Fragment {
public FragmentSix() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.six, container, false);
return rootView;
}
}
}
You have to replace the fragment using Transaction
See here:
http://developer.android.com/guide/components/fragments.html#Example
Check the showDetails(int index) method of TitlesFragment class:
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Use pager and give integer index to each fragment then use following code in itemclick
ViewPager pager;
pager.setCurrentItem(index, true);