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();
Related
Hey all I am having a little bit of an issue with trying to call a fragment that has the videoview within it into my current fragment page.
When I click on the test button I set up it goes through the code without error but never shows the video fragment - I even gave it a background color of red so I could see it load into my current view.
My goal here is just to send a parameter of the video path to the video fragment videoview player and start playing it.
videoPlay.java
public class videoPlay extends Fragment {
public videoPlay(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragvideoplay, container, false);
MediaController mc= new MediaController(getActivity());
VideoView view = (VideoView)rootView.findViewById(R.id.videoView);
String path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/sddir/Bubble Guppies.mp4";
view.setVideoURI(Uri.parse(path));
view.setMediaController(mc);
view.start();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
}
}
_fragvideoplayer.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<VideoView
android:id="#+id/videoView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
FragMovies.java:
public class FragMovies extends Fragment {
public FragMovies(){
//constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._fragmovies, container, false);
WebView view = (WebView) rootView.findViewById(R.id.webView);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
container.findViewById(R.id.webView).setVisibility(View.GONE);
container.findViewById(R.id.pBar1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
container.findViewById(R.id.pBar1).setVisibility(View.GONE);
container.findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setAllowContentAccess(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setLoadsImagesAutomatically(true);
view.getSettings().setAllowFileAccess(true);
view.getSettings().setBuiltInZoomControls(false);
view.getSettings().setDomStorageEnabled(true);
view.getSettings().setAppCacheEnabled(true);
view.getSettings().setDisplayZoomControls(false);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.getSettings().setSupportZoom(false);
view.setHorizontalScrollBarEnabled(false);
view.setVerticalScrollBarEnabled(false);
view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
view.loadUrl("https://www.bing.com/");
return rootView ;
}
}
_fragmovies.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainLayout">
<ProgressBar
android:id="#+id/pBar1"
android:layout_width="93dp"
android:layout_height="match_parent"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
android:layout_marginStart="950px"
android:layout_marginLeft="950px" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
Main_activity.java:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
PagerAdapter pagerAdapter;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getViews();
//adapter setup
pagerAdapter = new com.example.telluridetainment.PagerAdapter(getSupportFragmentManager());
//attaching fragments to adapter
pagerAdapter.addFragment(new FragMovies(),"Movies");
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
//setting icons
tabLayout.getTabAt(0).setIcon(R.drawable.ic_movie_white_24dp);
button = (Button) findViewById(R.id.button0);
button.setOnClickListener(new MyClass());
}
public class MyClass implements View.OnClickListener {
#Override
public void onClick(View v) {
videoPlay myfragment = new videoPlay();
//pass data
Bundle bundle = new Bundle();
bundle.putString("KEY","DATA");
myfragment.setArguments(bundle);
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentManager.addToBackStack(null);
fragmentManager.replace(R.id.viewPager, myfragment).commit();
}
}
private void getViews() {
tabLayout = findViewById(R.id.mTabLayout);
viewPager = findViewById(R.id.viewPager);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="2000px"
android:layout_height="1200px"
tools:context=".MainActivity">
<Button
android:id="#+id/button0"
android:layout_width="200dp"
android:layout_height="152dp"
android:text="Button"
android:textColor="#B71C1C" />
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/appbarLayout"
tools:ignore="SpeakableTextPresentCheck">
</android.support.v4.view.ViewPager>
</RelativeLayout>
The path to the movie is correct. And the movie is there in the "external" SD card path. Clicking around on the new fragment (videoPlay) yields no video menu (play, remind, pause...) so its not there.
Any help would be great!
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();
}
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
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);
How to go one Fragment to another when I will click on TextView Id?
Error shows:
java.lang.ClassCastException: com.example.tripigator.Overview cannot be cast to android.app.Activity.
and error comes from these lines :
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
So please anybody help me how to move from one fragment to another by clicking text item.
ProjectOverview class :
public class ProjectOverview extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project_overview);
initialingpaging();
TextView overview = (TextView) findViewById(R.id.txt_overview);
overview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);
}
});
}
private void initialingpaging() {
// TODO Auto-generated method stub
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Overview.class.getName()));
fragments.add(Fragment.instantiate(this, Highlight.class.getName()));
mPageAdapter = new PageAdapter(this.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)findViewById(R.id.viewpager);
pager.setAdapter(mPageAdapter);
}
}
Two Fragment Classes:
public class Overview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.overview,container,false);
}
}
public class Highlight extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
if(container == null)
{
return null;
}
return (LinearLayout) inflater.inflate(R.layout.highlight,container,false);
}
}
Layout Interface:
<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" >
<LinearLayout
android:id="#+id/project_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="65dp"
android:gravity="center" >
<TextView
android:id="#+id/txt_overview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Overview" />
<TextView
android:id="#+id/txt_highlite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginLeft="12dp"
android:text="Highlight" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
You can't initiate the fragment using Intent.Try this it helps.
Fragment fragment = null;
FragmentManager frgManager;
FragmentTransaction ft;
fragment = new Overview();
ft = frgManager.beginTransaction();
ft.replace(R.id.frame_content, fragment);
ft.addToBackStack(null);
ft.commitAllowingStateLoss();
If you use View-Pager
your_ViewPager.setCurrentItem(position)
you should not use intent in fragment to move another fragment
and check this for whole example http://examples.javacodegeeks.com/android/core/app/fragment/android-fragments-example/
use this.
((yourfragmentActivity) getActivity()).setCurrentItem(1,//desired activity 0=first 1= second and so on
true);
insted
Intent intent = new Intent(ProjectOverview.this, Overview.class);
startActivity(intent);