Android - Fragment from ArrayAdapter - java

At the moment I have a activity with a viewpager which inflates a listfragment.
When a user click on a item in the listview I would like to inflate a new fragment.
Test.java
public class Test extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
final Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ViewPager vp = (ViewPager) findViewById(R.id.n_Viewpager);
this.addPages(vp);
}
//ADD ALL PAGES
private void addPages(ViewPager pager) {
MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new TestFragment());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
}
layout.activity_test
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="tutorial.com.ScratchGolfer.Test">
<RelativeLayout
android:id="#+id/nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarr"
>
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/n_Viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appbarr"
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
/>
</RelativeLayout>
</RelativeLayout>
TestFragment.java
public class TestFragment extends ListFragment {
//Setting the name of each event
String[] options = {"1", "2", "3", "4", "5", "6", "7"};
ArrayAdapter<String> adapter;
//Inflating the view with the fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
adapter = new ArrayAdapter<>(getActivity(), R.layout.listitem, R.id.textview, options);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
//Click events
#Override
public void onStart() {
super.onStart();
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int pos, long l) {
switch (pos) {
case 0:
Intent intent0 = new Intent(v.getContext(), NewActivity.class);
v.getContext().startActivity(intent0);
break;
case 1:
break;
}
}
});
}
}
I have managed to open a activity when I click a item in the listview, but I would like to inflate the current activity with a new fragment depending on what item is clicked in the listview

It's not the best and shortest solution, but I found it more understandable.
You can create a Fragment as container and add it to your ViewPager. Then replace fragments inside it.
fragment_container.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container_root_view">
</LinearLayout>
ContainerFragment.Java
public class ContainerFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_container, container, false);
getChildFragmentManager().beginTransaction().replace(R.id.fragment_container_root_view, new TestFragment()).commit();
return view;
}
}
In you activity:
private void addPages(ViewPager pager) {
MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new ContainerFragment());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
In your TestFragment:
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int pos, long l) {
switch (pos) {
case 0:
getParentFragment().getChildFragmentManager().beginTransaction().replace(R.id.fragment_container_root_view, new SecondFragment()).addToBackStack("").commit();
break;
case 1:
break;
}
}
});
I didn't test this code to see if it has error or not, but with some changes, You can achieve to what you want.

Related

fragment with the listview is not being replaced by the fragment with the textview

I want to have a activity with a image and then two fragments, one fragment with a list view and other fragment with a textview.
So, when the image is clicked i want to show the fragment with the list view and when the item on the fragment is clicked i want to replace the fragment with the listview with the fragment with the textview showing the text of the clicked list item.
Im doing this with the code below, but its not working, when an item of the list item is clicked the fragment with the listview is not replaced by the fragment with the textview so the list item text dont appears.
Main activity class:
public class MainActivity extends AppCompatActivity {
private ImageView img;
FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
img = (ImageView) findViewById(R.id.imageView);
}
private void addFragment() {
Fragment fragment = new Fragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.listviewInFragment, fragment, "frag");
transaction.commit();
}
public void AddFragmentList(View view) {
Fragment fragment = new Fragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.container, new FragmentA(), "frag");
transaction.commit();
}
}
main activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/image"
android:onClick="AddFragmentList"
tools:layout_editor_absoluteY="71dp"
tools:layout_editor_absoluteX="0dp" />
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.0"
tools:layout_editor_absoluteY="390dp">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
Fragment with the list view:
public class FragmentA extends Fragment{
private ListView listItems;
private String[] items = {
"item1",
"item2",
"item3",
"item4"
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listItems = (ListView) getView().findViewById(R.id.listviewInFragment);
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1, items);
listItems.setAdapter(adapter);
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Toast.makeText(getActivity().getApplicationContext(), clickedValue, Toast.LENGTH_SHORT).show();
Bundle b = new Bundle();
b.putString("clickedValue", clickedValue);
FragmentA fragA = new FragmentA();
fragA.setArguments(b);
getFragmentManager().beginTransaction().replace(R.id.container, fragA);
}
});
}
}
Fragment with the list view xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0ff">
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="16dp"
android:id="#+id/listviewInFragment"/>
</android.support.constraint.ConstraintLayout>
Fragment with the text view:
public class fragmentb extends Fragment {
private TextView tv;
Intent intent;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
Bundle b = this.getArguments();
if(b != null){
String clickedValue =b.getString("clickedValue");
tv.setText(clickedValue);
}
}
}
Fragment with the text view xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="17dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
/>
</android.support.constraint.ConstraintLayout>
Try this, may help you
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int positionCode = i;
String clickedValue = (String) adapterView.getItemAtPosition(i);
Toast.makeText(getActivity().getApplicationContext(), clickedValue, Toast.LENGTH_SHORT).show();
Bundle b = new Bundle();
b.putString("clickedValue", clickedValue);
FragmentB fragb = new FragmentB();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragb);
fragmentTransaction.commit();
}

How can I add a ViewPager to a Navigation Drawer Item in Android application?

I want to add a viewPager for main fragment in my android app.
This is the xml file for main fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
This is the Java code for Main Fragment
public class MainFragment extends ListFragment {
private static final String TAG = MainFragment.class.getSimpleName();
private StudentsDBHandler studentsDBHandler;
public MainFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
studentsDBHandler = new StudentsDBHandler(getActivity());
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
displayStudents();
return rootView;
}
private void displayStudents() {
List<Student> studentList = studentsDBHandler.getAll();
ArrayAdapter<Student> list = new ArrayAdapter<>(getActivity(), R.layout.item_student, studentList);
setListAdapter(list);
}
}
You have a DrawerLayout page. It's about your drawer contains.
İn the DrawerLayout XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
add this code below
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
write this code and setup your View pager like example
viewPager=(ViewPager)findViewById(R.id.viewPager);
FragmentManager fm=getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fm));
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position==0)
fragment= new Home1();
if(position==1)
fragment=new Home2();
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
I hope Help you

accessing fragment's view from activity with function

I am trying to dynamically change a text from a fragment textview inside de activity but I keep getting 'cannot obtain root' error. I tried to instantiate the textview inside onCreateView and inside onActivityCreated as well but it doesnt work. How can I change the text from a fragment textview inside the activity?
Fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
Fragment Code:
public class TabFragment1 extends Fragment {
private TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv = (TextView) getView().findViewById(R.id.textView);
}
public void setText(String text){
tv.setText(text);
}
}
Main xml:
<RelativeLayout
android:id="#+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
Main code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
TabFragment1 t1 = new TabFragment1();
TabFragment2 t2 = new TabFragment2();
TabFragment3 t3 = new TabFragment3();
adapter.newFrag(t1);
adapter.newFrag(t2);
adapter.newFrag(t3);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
t1.setText("HELLO WORLD");
}
#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);
}
}
PagerAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
List<Fragment> aFrag;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
aFrag = new ArrayList<Fragment>();
}
public void newFrag(Fragment f){
aFrag.add(f);
}
#Override
public Fragment getItem(int position) {
return aFrag.get(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You try to set text on view, but this view wasn't created, this fragment wasn't created. If You want to set text from activity you can pass bundle to fragment arguments with that text, and in fragment chceck bundle and set text. Later if you want to change text in this fragment then you can use your function.
public class TabFragment1 extends Fragment {
private TextView tv;
public static TabFragment1 create(String text){
Bundle b = new Bundle();
b.putString("textdata",text);
TabFragment1 f = new TabFragment1();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
tv = (TextView) view.findViewById(R.id.textView);
if(getArguments()!=null){
tv.setText(getArguments().getString("textdata"));
}
return view;
}
public void setText(String text){
tv.setText(text);
}
}
In your activity create this fragment using static method:
TabFragment1 t1 =TabFragment1.create("HELLO WORLD");
Hardcore execution of your base code is:
new Handler().postDelayed(new Runnable(){t1.setText("HELLO WORLD");},300);

Unable to Replace Fragment A with Fragment B in same Activity

My App have one Main Activity which has a Linear Layout and Linear layout is showing one Fragment A having list containing Button and Text View. I want click on a Button of List view of Fragment A then It should Replace fragment A with Fragment B.
Now I am able to Click on the Button of list view of Fragment A but(it is not showing Fragment B) it is showing Android not responding. I have done Debug and I am Getting error at committing of transaction for Fragment B. other piece of Code is Working Fine.
Please help me out why I am getting this error
Full code is below
Main Activity Code
public class MainActivity extends Activity {
FrameLayout frameLayout = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Async","On Create");
frameLayout = (FrameLayout) findViewById(R.id.fragment_Container);
InstallFragmetA();
}
protected void InstallFragmetA()
{
FragmentA fragmentA = new FragmentA();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentA,"A");
transaction.commit();
}
protected void InstallFragmetB()
{
FragmentB fragmentB = new FragmentB();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentB,"B");
transaction.commit();
}
protected void RemoveFragmetA()
{
Log.d("Async","In Remove Fragment A");
FragmentB fragmentB = new FragmentB();
Log.d("Async","Fragment b initializeed");
// FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Log.d("Async","Begin fragment transaction");
FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("A");
// fragmentA.onDestroy();
// fragmentA.onDestroyView();
transaction.replace(R.id.fragment_Container, fragmentB, "B");
Log.d("Async", "Fragment A replaced");
// transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Log.d("Async","Fragment Failed");
// transaction.addToBackStack(null);
transaction.commit();
Log.d("Async","Transaction Commit");
}
Fragment A Code
public class FragmentA extends Fragment {
MainActivity mainActivity= null;
TextView textView=null;
String[] friendList= null;
public FragmentA()
{
mainActivity = new MainActivity();
}
//Activity activity= null;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async","On Create");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async","On Create view");
return inflater.inflate(R.layout.fragmenta,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView = (TextView) getActivity().findViewById(R.id.textView);
ListView list = (ListView) getActivity().findViewById(R.id.listView);
Log.d("Async","Array is "+getResources().getStringArray(R.array.FriendsList));
friendList = getResources().getStringArray(R.array.FriendsList);
Log.d("Async","Array is "+friendList[0]);
textView.setText(friendList[0]);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.FriendsList,R.layout.text);
AdapterClass adapterClass = new AdapterClass(getActivity(),friendList,mainActivity);
list.setAdapter(adapterClass);
list.setItemsCanFocus(true);
list.setFocusable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Async","A");
Toast.makeText(getActivity(),"Hello "+position,Toast.LENGTH_LONG).show();
}
});
Log.d("Async","On Activity Created");
}
}
Adapter Class Which I am Using for Fragment A
public class AdapterClass extends ArrayAdapter {
Button btn;
int counter=0;
Context c=null;
String[] friendList= null;
LayoutInflater l;
MainActivity mainActivity = null;
public AdapterClass(Context c, String[] friendList, MainActivity mainActivity) {
super(c,R.layout.a,R.id.textView3,friendList);
l = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
Log.d("Async","counter is ");
this.c=c;
this.friendList = friendList;
this.mainActivity = mainActivity;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("Async","getView is "+position);
Log.d("Async","counter is "+counter);
View row = convertView;
Myholder holder = null;
if(row == null)
{
Log.d("Async","Row is Null");
row = l.inflate(R.layout.a, parent,false);
holder = new Myholder(row);
row.setTag(holder);
Log.d("Async","Row Set tag");
}
else
{
Log.d("Async","Row is not null");
holder = (Myholder) row.getTag();
Log.d("Async","Holder not tag");
}
holder.btn.setText(friendList[position]);
holder.text.setText(friendList[position]);
holder.btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Async","Button Clicked "+friendList[position]);
Toast.makeText(c,"Button clicked "+friendList[position],Toast.LENGTH_LONG).show();
mainActivity.RemoveFragmetA();
}
});
return row;
}
}
Fragment B Code
public class FragmentB extends Fragment {
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async", " Fragment B On Create");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async"," Fragment B On Create view");
return inflater.inflate(R.layout.fragmentb,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:id="#+id/mainActivity"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:id="#+id/fragment_Container"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></FrameLayout>
fragmenta.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="#+id/linearLayouts"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
fragmentb.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="#+id/textView" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
I am getting bellow Error.
E/AndroidRuntime(1021): java.lang.IllegalStateException: Activity has been destroyed
E/AndroidRuntime(1021): at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commit(BackStackRecord.java:574)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.MainActivity.InstallFragmetB(MainActivity.java:38)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.AdapterClass$1.onClick(AdapterClass.java:64)
E/AndroidRuntime(1021): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(1021): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(1021): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(1021): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(1021): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1021): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(1021): at dalvik.system.NativeStart.main(Native Method)
MainActivity
public class MainActivity extends Activity implements FragmentAListener
{
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = (FragmentA) getFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
if (savedInstanceState == null) {
fragmentA = new FragmentA();
replaceToFragment(fragmentA, false);
}
}
#Override
public void onListItemButtonClicked(String itemName) {
fragmentB = new FragmentB();
Bundle bundle = new Bundle();
bundle.putString(FragmentB.ITEM_NAME_KEY, itemName);
fragmentB.setArguments(bundle);
replaceToFragment(fragmentB, true);
}
public void replaceToFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (addToBackStack) {
transaction.addToBackStack(fragment.getClass().getSimpleName());
}
transaction.commit();
}
}
FragmentA
public class FragmentA extends Fragment
{
private String[] friendList;
private FragmentAListener listener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof FragmentAListener)) {
throw new RuntimeException("Activity must implements FragmentAListener");
}
listener = (FragmentAListener) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenta, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
ListView listView = (ListView) view.findViewById(R.id.listView);
friendList = getResources().getStringArray(R.array.FriendsList);
textView.setText(friendList[0]);
AdapterClass adapterClass = new AdapterClass(inflater.getContext(), friendList, listener);
listView.setAdapter(adapterClass);
listView.setOnItemClickListener(itemClickListener);
return view;
}
private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO your code
}
};
public interface FragmentAListener
{
void onListItemButtonClicked(String itemName);
}
}
FragmentB
public class FragmentB extends Fragment
{
public static final String ITEM_NAME_KEY = "item_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentb, container, false);
//TODO find your views here
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("Its FragmentB. Selected item: " + getArguments().getString(ITEM_NAME_KEY));
return view;
}
}
Adapter
public class AdapterClass extends ArrayAdapter<String>
{
private LayoutInflater inflater;
private FragmentAListener listener;
public AdapterClass(Context context, String[] friendList, FragmentAListener listener) {
super(context, 0, friendList);
inflater = LayoutInflater.from(context);
this.listener = listener;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
Holder holder;
if (view == null) {
view = inflater.inflate(R.layout.list_item, parent, false);
holder = new Holder(view);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
String itemName = getItem(position);
holder.textView.setText(itemName);
holder.button.setText(itemName);
holder.button.setTag(itemName);
return view;
}
private class Holder
{
private TextView textView;
private Button button;
public Holder(View row) {
textView = (TextView) row.findViewById(R.id.textView);
button = (Button) row.findViewById(R.id.button);
button.setOnClickListener(onClickListener);
}
}
private OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View v) {
listener.onListItemButtonClicked(v.getTag().toString());
}
};
}
Activity layout
<LinearLayout
android:id="#+id/mainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
FragmentA layout
<LinearLayout android:id="#+id/linearLayouts"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment A"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
FragmentB Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment B"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
List Item Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/fancy_item_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:padding="15dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Text"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>
Add this on your activity.xml, container for Fragment
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentcontainer">
</FrameLayout>
and this for attach Fragment
Fragment fr;
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fr = new YourFragmentToShow();
fragmentTransaction.replace(R.id.fragmentcontainer, fr)
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();

Click a button to open a Fragment?

I have a ViewPager in which I am able to view between 4 different tabs (which are fragments) I created. In one of my fragments, I want to have a button that will, after I click a button on that page, replace that view with another fragment. Now I don't want to swipe to another tab, I just merely want to replace the view of the current fragment when I press that button. Here is my attempt, but I'm not sure why when I click my button, nothing happens. If anyone could help me that would be great. Thanks!
This is the Fragment I call to create the view and the button I want to press.
ManualSelection.java
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
return rootView;
}
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
}
}
And here is the Fragment I want to create
ManualSelectionListView.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ManualSelectionListView extends Fragment {
static final String[] MOBILE_OS =
new String[] { "Android", "iOS", "WindowsMobile", "Blackberry"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.listview, container, false);
ListView lv = (ListView)rootView.findViewById(R.id.listview);
lv.setAdapter(new MobileArrayAdapter(getActivity(),MOBILE_OS));
return rootView;
}
}
And here are my XML files:
activity_manual_selection.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.ecs160.homestay.ManualSelection"
android:id="#+id/fragmentTest">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate"
android:id="#+id/manual_generate"
android:layout_centerHorizontal="true"
android:onClick="generateListView"/>
And here is the XML file called listview.xml that contains R.id.listView_manual
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/listView_manual">
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
I get nothing displayed when I hit "Generate." Any ideas? Thanks!
In your Activity you should create this:
public void generateListView(View v){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
The problem is that you are trying to get the Button id from your main activity which will return null
Button listViewGenerated = (Button) getActivity().findViewById(R.id.manual_generate);
Button manual_generate is located in your activity_manual_selection layout not in your Main activity's layout you cant get view from different layout or else it will return null
solution:
Get the Button's id from your fragment's layout
public class ManualSelection extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.activity_manual_selection, container, false);
intent = new Intent(getActivity(), ManualSelectionListView.class);
Button listViewGenerated = (Button) rootView.findViewById(R.id.manual_generate);
listViewGenerated.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.listView_manual, new ManualSelectionListView());
ft.commit();
}
});
return rootView;
}
remove onActivityCreated

Categories

Resources