How to combine two functions together in Java android - android

How can i be able to combine these two functions into just one and to be able to perform two actions Invisible and invisible. I dont wanna just get the if statment from buttonInVisible method and just put in in the buttonVisible one.
Here is the code
MainActivity
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
private WebViewFragment mWebViewFragment;
public TextView textView;
public Button buttons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = (Button) findViewById(R.id.button);
buttons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
textView = (TextView) findViewById(R.id.textViewId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mWebViewFragment = new WebViewFragment();
fragmentTransaction.replace(R.id.mainFragment, mWebViewFragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
if(mWebViewFragment != null && mWebViewFragment.canGoBack()) {
mWebViewFragment.goBack();
} else {
super.onBackPressed();
}
}
public void setTitle(String title) {
if(textView != null){
textView.setText(title);
}
}
public void buttonVisible(int visibility) {
if(buttons != null){
buttons.setVisibility(visibility);
}
}
#Override
protected void onStart() {
super.onStart();
setVisible(true);
}
}
Fragment
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewFragment extends Fragment {
private WebView mWebView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mWebView = (WebView) view.findViewById(R.id.webView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("https://www.google.co.uk/");
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.v("WebView has started", url);
}
#Override
public void onPageFinished(WebView view, String url) {
String title = mWebView.getTitle();
Log.v(getClass().getName(), "Title=" + title);
/**if(mWebView.canGoBack()) {
buttonVisible();
} else {
buttonInVisible();
}**/
}
});
mWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
setTitle(title);
Log.v(getClass().getName(), "Received Title" + title);
}
});
return view;
}
public boolean canGoBack() {
return mWebView.canGoBack();
}
public void goBack() {
mWebView.goBack();
}
public void setTitle(String title) {
if (title != null && title.length() > 0) {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity){
((MainActivity) activity).setTitle(title);
}
}
}
public void SetVibility() {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity) {
((MainActivity) activity).buttonVisible(View.VISIBLE);
}
}
public void buttonInVisible() {
Activity activity = getActivity();
if(activity != null && activity instanceof MainActivity){
((MainActivity) activity).buttonVisible(View.INVISIBLE);
}
}
}

public void changeButtonVisibilityState() {
button.setVisibility(button.getVisibility() == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
}

Since the method
public void buttonVisible(int visibility) {
if(buttons != null){
buttons.setVisibility(visibility);
}
}
Is public on the MainActivity (which contains the fragment), you can simply invoke on your fragment when you want the following :
((MainActivity) getActivity).buttonVisible(View.VISIBLE)
This will call the MainActivity and change the visibility of the button on it

Related

My Webview in fragment always refresh when i switch my tab from one to other

I want to save instant of my fragment and then restore back on reopening the tab. when switching from one tab to other.
here is my fragment code:
package com.mhm.universityofwah.fragments;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.mhm.universityofwah.R;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;
public class WebFragment extends Fragment implements WaveSwipeRefreshLayout.OnRefreshListener {
private WaveSwipeRefreshLayout swipeRefreshLayout;
private WebView mWebView;
private Activity context;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
View view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
return view;
}
private BottomNavigationView.OnNavigationItemSelectedListener navListner=
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_refresh:
mWebView.reload();
break;
case R.id.nav_back:
if(mWebView.canGoBack()){
mWebView.goBack();
}
break;
case R.id.nav_forward:
if(mWebView.canGoForward()){
mWebView.goForward();
}
break;
}
return true;
}
};
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void loadWebsite() {
ConnectivityManager cm = (ConnectivityManager) Objects.requireNonNull(getActivity()).getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("http://uow.edu.pk");
} else {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
swipeRefreshLayout.setRefreshing(false);
}
}
public class Callback extends WebViewClient {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(Objects.requireNonNull(getActivity()).getApplicationContext(), "Please Check Network Connection!", Toast.LENGTH_SHORT).show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.contains("mailto:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
}else {
view.loadUrl(url);
return true;
}
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
}
#Override
public void onRefresh() {
mWebView.reload();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
}
#Override
public void onSaveInstanceState(#NotNull Bundle outState )
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public boolean onKey(View v, int keyCode, KeyEvent event ) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
Objects.requireNonNull(getActivity()).finish();
}
return true;
}
}
// here your code
return false;
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
this.context = (Activity) context;
}
}
I have 4 tabs but when i switch from one tab to other and come back to first one, it always reload. i tried every thing but my problem is not solved. Please help me to get this thing done.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setRetainInstance(true);
if(view == null){
view = inflater.inflate(R.layout.fragment_avicenna, container, false);
mWebView = (WebView) view.findViewById(R.id.webview);
swipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setOnRefreshListener((WaveSwipeRefreshLayout.OnRefreshListener) WebFragment.this);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
swipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
BottomNavigationView bottomNavigationView=view.findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListner);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setWebViewClient(new Callback());
if(savedInstanceState==null){
loadWebsite();
}
}
return view;
}
please make view a global variable and add null check when your onCreate view recalls it recreates the view so add check that if view != null then only return already initialized view instead of creating again

Fragment dynamic layout save ui changes screen orientation

I am trying to maintain the ui changes so that when restarting the activity, the instance of my fragment become used with the changes of the buttons. So I found setRetainInstance(true) doesn't destroy the fragment object, however, the resulted view is destroyed. So I overrode onSaveInstance in the fragment class to save the ids of the resources that is called in the event handlers for setting it the next time the activity is created. The result was unexpected, at least for me:
1. The view of the fragment is destroyed when recreating the activity and the fragments instance become reattached to the new activity instance.
2. Event handlers become non-operational, so I don't know where is the problem.
Here is the code of the activity class:
package com.voicenoteinc.ticatactoy;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
Tic_Fragment s;
FragmentManager manager;
String TAG_FRAGMENT = "tag_fragment";
FragmentTransaction trans;
boolean retained = true;
String COLOR_ARRAY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = getFragmentManager();
s = (Tic_Fragment) manager.findFragmentByTag(TAG_FRAGMENT);
if(s == null){
s = new Tic_Fragment();
retained = false;
trans = manager.beginTransaction();
trans.add(R.id.fragment_container,s,TAG_FRAGMENT).commit();
}
}
}
and Here is the code for the Fragment class:
package com.voicenoteinc.ticatactoy;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Switch;
public class Tic_Fragment extends Fragment {
public Button bu1,bu2,bu3,bu4,bu5,bu6,bu7,bu8,bu9;
int COLOR[] = new int[9];
public String COLOR_KEY = "COLOR_KEY";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
return inflater.inflate(R.layout.tic_fragment,container,false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
for(int i =0; i<9;i++){
COLOR[i] = R.color.granite;
}
super.onViewCreated(view, savedInstanceState);
if(savedInstanceState!=null){
COLOR=savedInstanceState.getIntArray(COLOR_KEY);
bu1.setBackgroundResource(COLOR[0]);
bu2.setBackgroundResource(COLOR[1]);
bu3.setBackgroundResource(COLOR[2]);
bu4.setBackgroundResource(COLOR[3]);
bu5.setBackgroundResource(COLOR[4]);
bu6.setBackgroundResource(COLOR[5]);
bu7.setBackgroundResource(COLOR[6]);
bu8.setBackgroundResource(COLOR[7]);
bu9.setBackgroundResource(COLOR[8]);
}else{
bu1 = getView().findViewById(R.id.bu1);
bu2 = getView().findViewById(R.id.bu2);
bu3 = getView().findViewById(R.id.bu3);
bu4 = getView().findViewById(R.id.bu4);
bu5 = getView().findViewById(R.id.bu5);
bu6 = getView().findViewById(R.id.bu6);
bu7 = getView().findViewById(R.id.bu7);
bu8 = getView().findViewById(R.id.bu8);
bu9 = getView().findViewById(R.id.bu9);
}
eventhandlers();
}
public void eventhandlers(){
bu1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu1,1);
}
});
bu2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu2,2);
}
});
bu3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu3,3);
}
});
bu4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu4,4);
}
});
bu5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu5,5);
}
});
bu6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu6,6);
}
});
bu7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu7,7);
}
});
bu8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu8,8);
}
});
bu9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display(bu9,9);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putIntArray(COLOR_KEY,COLOR);
}
public void display(Button bu, int i){
int backgroundColor = R.color.greenery;
bu.setBackgroundResource(backgroundColor);
COLOR[i-1] = backgroundColor;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
Thank ou for helping, and by the way I am new to using Fragments and Dynamic Layouts

my fragment showing blank screen after i am having this code

package com.example.mindwareuae;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class FacebokkFragment extends Fragment{
private LoginButton loginBtn;
private Button postImageBtn;
private Button updateStatusBtn;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
try
{
View rootView = inflater.inflate(R.layout.fragment_facebook,container,false);
userName = (TextView)rootView.findViewById(R.id.user_name);
loginBtn = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
postImageBtn = (Button)rootView.findViewById(R.id.fbpost_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});
updateStatusBtn = (Button)rootView.findViewById(R.id.fbupdate_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonsEnabled(false);
}catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void buttonsEnabled(boolean isEnabled) {
postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(getActivity(),
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
}
// public void postStatusMessage() {
// if (checkPermissions()) {
// Request request = Request.newStatusUpdateRequest(
// Session.getActiveSession(), message,
// new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// if (response.getError() == null)
// Toast.makeText(getActivity(),
// "Status updated successfully",
// Toast.LENGTH_LONG).show();
// }
// });
// request.executeAsync();
// } else {
// requestPermissions();
// }
// }
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
// #Override
// public void onResume() {
// super.onResume();
// uiHelper.onResume();
// buttonsEnabled(Session.getActiveSession().isOpened());
// }
//
// #Override
// public void onPause() {
// super.onPause();
// uiHelper.onPause();
// }
//
// #Override
// public void onDestroy() {
// super.onDestroy();
// if (rootView != null) {
// ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
// if (parentViewGroup != null) {
// parentViewGroup.removeAllViews();
// }
// }
// uiHelper.onDestroy();
// }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
i want login the facbook from this fragment..but i am not getiing any thing my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp"
android:background="#EEEEEE">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/fb_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="18sp" />
<Button
android:id="#+id/fbupdate_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="update_status" />
<Button
android:id="#+id/fbpost_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post_image" />
</LinearLayout>
it is my xml file why i am not able to get the fragment with my facebook login button.
please any one can explain me.
Create a FragmentActivity and add your fragment to that FragmentActivity
public class MainActivity extends FragmentActivity{
FacebokkFragment fbFragment;
ArrayList<Fragment> fragemetnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fbFragment = new FacebokkFragment();
fragemetnList = getFragmnetsList();
setContentView(R.layout.activity_main);
}
ArrayList<Fragment> getFragmnetsList() {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(fbFragment);
// you can also add more fragments here
return fragments;
}
}
Now create an activity_main.xml file into your res/layout directory
Don't forget to make the entry of your MainActivity into AndroidManifest.xml file
May this code will solve your problem
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
Is this part of code really required? Try removing this.
Try this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
...
return rootView;

Web View Fragment html embeed video fullscreen suport

Hello everyone i got a question regarding how to enable full screen support in html embed videos on my webview i have hardware accelerated true on manifest and the video works ok but wen pressed to go fullscreen the video stops.
here is my code
import com.photoshop.video.tutorials.R;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebViewFragment extends Fragment {
public final static String TAG = WebViewFragment.class.getSimpleName();
private WebView viewContentWebView;
private String url;
private boolean resetHistory = true;
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.webview, container, false);
final ProgressBar viewContentProgress = (ProgressBar) v.findViewById(R.id.progress);
viewContentWebView = (WebView) v.findViewById(R.id.webview);
viewContentWebView.getSettings().setJavaScriptEnabled(true);
viewContentWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
viewContentWebView.loadUrl("file:///android_asset/myerrorpage.html");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
viewContentWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
viewContentProgress.setProgress(newProgress);
viewContentProgress.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
if (newProgress == 100 && resetHistory) {
viewContentWebView.clearHistory();
resetHistory = false;
}
}
});
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
reload();
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden)
viewContentWebView.stopLoading();
else
reload();
}
public void setUrl(String url) {
this.url = url;
if (viewContentWebView != null)
viewContentWebView.stopLoading();
resetHistory = true;
}
public void reload() {
if (TextUtils.isEmpty(url))
return;
viewContentWebView.loadUrl(url);
}
public boolean onBackPressed() {
if (viewContentWebView.canGoBack()) {
viewContentWebView.goBack();
return true;
}
return false;
}
}
How can i achieve this
many thanks in advance and a little patience with me because i am very very VERY new to android
You should override the two following methods in your WebChromeClient:
public void onShowCustomView(View view, CustomViewCallback callback);
public void onHideCustomView();
This is an extract of the code I'm using:
private View mCustomView;
private class MyWebChromeClient extends WebChromeClient {
private int mOriginalOrientation;
private FullscreenHolder mFullscreenContainer;
private CustomViewCallback mCustomViewCollback;
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mOriginalOrientation = mActivity.getRequestedOrientation();
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
mFullscreenContainer = new FullscreenHolder(mActivity);
mFullscreenContainer.addView(view, ViewGroup.LayoutParams.MATCH_PARENT);
decor.addView(mFullscreenContainer, ViewGroup.LayoutParams.MATCH_PARENT);
mCustomView = view;
mCustomViewCollback = callback;
mActivity.setRequestedOrientation(mOriginalOrientation);
}
#Override
public void onHideCustomView() {
if (mCustomView == null) {
return;
}
FrameLayout decor = (FrameLayout) mActivity.getWindow().getDecorView();
decor.removeView(mFullscreenContainer);
mFullscreenContainer = null;
mCustomView = null;
mCustomViewCollback.onCustomViewHidden();
// show the content view.
mActivity.setRequestedOrientation(mOriginalOrientation);
}
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}

How can I make a fragment replace actionbar menu behavior?

Before I start, yes I have read countless related questions. I still can't seem to track down the issue.
I have a SherlockFragmentActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.Fragment;
public class FragmentActivity extends BaseActivity {
public static final String TAG = "FragmentActivity";
public static final int SCHEDULE_FRAGMENT = 0;
public static final int MAP_FRAGMENT = 1;
public static final int FOOD_FRAGMENT = 2;
public static final int TWITTER_FRAGMENT = 3;
public static final int HASHTAG_FRAGMENT = 4;
private Fragment mContent;
public FragmentActivity() {
super(R.string.main_activity_title);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_frame);
switchContent(SCHEDULE_FRAGMENT);
setBehindContentView(R.layout.menu_frame);
}
public void switchContent(int id) {
getFragment(id);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent)
.commit();
getSlidingMenu().showContent();
}
private void getFragment(int id) {
switch (id) {
case 0:
mContent = new ScheduleFragment();
break;
case 1:
mContent = new FoodFragment();
break;
case 2:
mContent = new MapFragment();
break;
case 3:
mContent = new TwitterFragment();
break;
case 4:
mContent = new HashtagFragment();
break;
}
}
}
It extends BaseActivity:
package com.kicklighterdesignstudio.floridaday;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.MenuItem;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;
public class BaseActivity extends SlidingFragmentActivity {
// private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
// mTitleRes = titleRes;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setTitle(mTitleRes);
setTitle("");
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new MenuFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(
R.id.menu_frame);
}
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
sm.setBehindScrollScale(0.0f);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Right now, I'm only concerned with ScheduleFragment:
package com.kicklighterdesignstudio.floridaday;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragment;
public class ScheduleFragment extends SherlockFragment implements OnItemClickListener {
public static final String TAG = "ScheduleFragment";
private ArrayList<ScheduleItem> schedule;
private FloridaDayApplication app;
public ScheduleFragment() {
// setRetainInstance(true);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedule_fragment, container, false);
}
#Override
public void onStart() {
super.onStart();
getSherlockActivity().getSupportActionBar().setTitle(R.string.schedule_fragment);
schedule = app.getSchedule();
ListView scheduleListView = (ListView) getActivity().findViewById(R.id.schedule_list);
ScheduleItemAdapter adapter = new ScheduleItemAdapter(getActivity(), schedule);
scheduleListView.setAdapter(adapter);
scheduleListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> a, View v, int id, long position) {
Fragment newFragment = new ScheduleItemFragment(id);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame, newFragment).addToBackStack(null).commit();
}
}
ScheduleFragment displays a list of schedule items. When clicked, a new fragment is displayed (ScheduleItemFragment) to show details of the item and a map to its location:
package com.kicklighterdesignstudio.floridaday;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.MarkerOptions;
#SuppressLint("ValidFragment")
public class ScheduleItemFragment extends SherlockFragment {
public static final String TAG = "ScheduleItemFragment";
private int scheduleItemId;
private FloridaDayApplication app;
private ScheduleItem scheduleItem;
private MapView mapView;
private GoogleMap map;
public ScheduleItemFragment(int id) {
scheduleItemId = id;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = (FloridaDayApplication) activity.getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.schedule_item_fragment, container, false);
setHasOptionsMenu(true);
// Initialize MapView
mapView = (MapView) v.findViewById(R.id.map_view);
mapView.onCreate(savedInstanceState);
return v;
}
#Override
public void onStart() {
super.onStart();
scheduleItem = app.getSchedule().get(scheduleItemId);
getSherlockActivity().getSupportActionBar().setTitle(scheduleItem.getTitle());
// Map Stuff
map = mapView.getMap();
if (map != null) {
map.getUiSettings();
map.setMyLocationEnabled(true);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Add marker to the map
MarkerOptions options = new MarkerOptions().position(scheduleItem.getLocation().getPosition()).title(
scheduleItem.getLocation().getTitle());
map.addMarker(options);
// Adjust Camera Programmatically
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
scheduleItem.getLocation().getPosition(), 14);
map.animateCamera(cameraUpdate);
} else {
Log.i(TAG, "Map is null");
}
// Other Views
TextView title = (TextView) getSherlockActivity().findViewById(R.id.title);
TextView time = (TextView) getSherlockActivity().findViewById(R.id.time);
TextView description = (TextView) getSherlockActivity().findViewById(R.id.description);
title.setText(scheduleItem.getTitle());
time.setText(scheduleItem.getDateTimeString());
description.setText(scheduleItem.getDescription());
}
// TODO: Make this work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}
#Override
public void onPause() {
mapView.onPause();
super.onPause();
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onSaveInstanceState(Bundle outState) {
mapView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
}
Thanks to BaseActivity, the icon in my ActionBar is clickable. It toggles the Sliding Menu. When viewing a ScheduleItemFragment, I would like the icon to return to the previous item in the backstack (which you can see I'm trying to do.) No matter what I try, the icon always toggles the Sliding Menu. Any thoughts on how to guarantee my Fragment gains control of the ActionBar menu clicks?
you need to call setHasOptionsMenu(true); in onCreate, not onCreateView
also I'm interested what happens when you debug, does onOptionsItemSelected still get called?
edit: add the following to your fragment
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
edit1:
there may be a better way to do this but I'm not exactly sure how your fragments are setup out, create a public field in baseActivity public bool isItemFragmentOnTop
now onOptionsItemSelected in the case of the home button getting press do this
if (isItemFragmentOnTop){
getFragmentManager().popBackStack();
isItemFragmentOnTop = false;
} else {
toggle();
}
return true;
then in your fragment you can call ((BaseActivity)getActivity).isItemFragmentOnTop = true; to make the home button pop the back stack, you would want to do this when you display your fragment onItemClick in your list view.

Categories

Resources