Android videoView not showing inside fragment - java

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!

Related

Changing my Google Map from type FragmentActivity to a simple Fragment for a BottomNavigationView?

I wanted to implement a BottomNavigationView (toolbar at the bottom) in my app. My GoogleMap fragment is of type FragmentActivity, not fragment. Would this be a problem? Is there an easy way to convert it to a fragment? I've checked a lot of tutorials and none of them fit the situation I'm in or address it at all. Thanks in advance.
Hope this answer can help you !
Example Activity
public class ExampleActivity extends AppCopmactActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example_activity);
initFragment(savedInstanceState);
}
private void initFragment(Bundle savedInstanceState) {
if (findViewById(R.id.mainFragmentContainer) != null) {
if (savedInstanceState != null) {
return;
}
ExampleFragment exampleFragment = new ExampleFragment ();
getSupportFragmentManager().beginTransaction().add(R.id.mainFragmentContainer, exampleFragment ).commit();
}
}
Example Fragment
public class ExampleFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_example, container, false);
return view;
}
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
example_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.Base">
</android.support.v7.widget.Toolbar>
<FrameLayout
android:id="#+id/mainFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tool_bar" />
</LinearLayout>

Add FragmentTabHost inside fragment

I have an application with a side menu created from fragments.
The problem comes when I want to create tabs in one of the fragments.
I have tried many examples and not work for me.
fragment_home.xml
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:orientation="horizontal"
></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
></FrameLayout>
</LinearLayout>
FragmentHome.java
public class FragmentInicio extends Fragment {
private FragmentTabHost mTabHost;
public FragmentInicio() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_home, container, false);
try{
//HERE TABHOST????
}catch(Exception e){
Log.e("UDI", e.getMessage());
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.d("EVENT", "OnCreate");
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(1);
}
}
What can I do?
Example:
http://webdemo.com.es/sample2.jpg
Thank you!
I know I'm late but this might help someone else.
To use FragmentTabHost inside fragment you can do this.
Create layout resource file
fragment_tab_host.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
FrameLayout with id realtabcontent is which will show current tab content which is in this case FirstFragment, SecondFragment and ThirdFragment
TabHostWidgetFragment.java code will be
public class TabHostWidgetFragment extends Fragment {
private static final String TAG = TabHostWidgetFragment.class.getSimpleName();
public TabHostWidgetFragment() { }
private FragmentTabHost fragmentTabHost;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: ");
return inflater.inflate(R.layout.fragment_frag_tab_host_widget, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i(TAG, "onViewCreated: ");
fragmentTabHost = view.findViewById(android.R.id.tabhost);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: ");
fragmentTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("First Tab").setIndicator("First Tab"), FirstFragment.class, null);
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Second Tab").setIndicator("Second Tab"), SecondFragment.class, null);
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Third Tab").setIndicator("Third Tab"), ThirdFragment.class, null);
}
public class FirstFragment extends Fragment {
private static final String TAG = FirstFragment.class.getSimpleName();
public FirstFragment() { }
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: ");
return inflater.inflate(R.layout.fragment_first, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i(TAG, "onViewCreated: ");
}
}
public class SecondFragment extends Fragment {
private static final String TAG = SecondFragment.class.getSimpleName();
public SecondFragment() { }
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: ");
return inflater.inflate(R.layout.fragment_second, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i(TAG, "onViewCreated: ");
}
}
public class ThirdFragment extends Fragment {
private static final String TAG = ThirdFragment.class.getSimpleName();
public ThirdFragment() { }
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
Log.i(TAG, "onCreateView: ");
return inflater.inflate(R.layout.fragment_third, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i(TAG, "onViewCreated: ");
}
}
}
Layout resources for FristFragment, SecondFragment and ThirdFragment
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/firstTab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/nature1"/>
</LinearLayout>
fragment_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/secondTab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/nature2"/>
</LinearLayout>
fragment_third.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/thirdTab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerInside"
android:src="#drawable/nature3"/>
</LinearLayout>
If you want to make it swipeable then add ViewPager after FrameLayout with id realtabcontent as written below and implement viewPager logic.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"/>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
And TabHostWidgetFragment.java class will be
Create separate or inner MyTabFactory.java class
public class MyTabFactory implements TabHost.TabContentFactory {
private final Context context;
public MyTabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String s) {
View v = new View(context);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
And then add tabs to tabhost like this. This is essential to setContent with MyTabFactory. If you add tabs like I mentioned above in code snippet, there will be issue which is, It will add fragments two times, one because of TabHost and one because of ViewPager.
fragmentTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("First Tab").setIndicator("First Tab").setContent(new MyTabFactory(getActivity())));
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Second Tab").setIndicator("Second Tab").setContent(new MyTabFactory(getActivity())));
fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Third Tab").setIndicator("Third Tab").setContent(new MyTabFactory(getActivity())));
You can either use android.support.v4.app.FragmentTabHost or TabHost It will work same for both.

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();

Fragment Dialog without Title issue

i'm trying to create a fragment dialog and need the full space to display information. so i want to disable the titlebar. But after i disabled it the isn't maximized in width anymore.
public class ArticleSearchFragment extends DialogFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, getTheme());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.article_search, container, false);
...
}
And the 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:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/searchField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Ean / Name / Produkt Nummer"
android:completionThreshold="1" />
<Button
android:id="#+id/cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/cancel" />
</LinearLayout>
put this code in your onCreateView() of dialog fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_image, null);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
It will remove title bar from Dialog Fragment

setRetainInstance not retaining the instance

I'm trying to use setRetainInstance() but it seems not working for me! =(.
I simplified the problem to the easiest version:
I have a fragment with a TextView and a Button.
The initial text of the TextView is "I'm waiting" when the button is pressed the text changes to "Hello!"
That is my code:
The fragment:
public class SayHelloFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text.setText("Hello!");
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
The Activity:
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
The activity's layout:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/say_hello_fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.example.retaintext.SayHelloFragment" />
The Fragment's layout:
<?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:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I&apos;m Waiting"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
But when I play it, press the button and change the device's orientation the text becomes reset.
What am I missing? How can I solve it? Thanks!
You are missing that onCreateView runs after the rotation again and inflates the default view with the default text again.
You need to restore the state of your views manually, e.g.:
public class SayHelloFragment extends Fragment {
private String mText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.say_hello_layout, container);
final TextView text = (TextView) view.findViewById(R.id.textView1);
if (mText != null)
text.setText(mText);
view.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mText = "Hello!";
text.setText(mText);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}

Categories

Resources