I'm new to programming .
I make an app that contains 3 Tabs with viewpager. 1st tab is a list of Button with their respective link. 2nd Tab is a WebView that will load url passed from the 1st tab when the users clicked on the link. 3rd tab is my Download Manager.
This is my MainActivity:
public class MainActivity extends SherlockFragmentActivity{
ActionBar mActionBar;
Button button;
ViewPager mPager;
Tab tab;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBar = getSupportActionBar();
// Hide Actionbar Icon
mActionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
mActionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//For ViewPager
mPager = (ViewPager) findViewById(R.id.pager);
//Activate FragmentManger
FragmentManager fm= getSupportFragmentManager();
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position){
super.onPageSelected(position);
mActionBar.setSelectedNavigationItem(position);//find the viewPager Potision
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_home).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_browse).setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setIcon(R.drawable.button_downloads).setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
My FragmentTab1:
public class FragmentTab1 extends SherlockFragment implements OnClickListener{
FragmentTab2 fTab2;
ViewPager viewPager;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
webview = (WebView) view.findViewById(R.id.webView1);
view.findViewById(R.id.Button01).setOnClickListener(this);
view.findViewById(R.id.Button02).setOnClickListener(this);
view.findViewById(R.id.Button03).setOnClickListener(this);
view.findViewById(R.id.Button04).setOnClickListener(this);
view.findViewById(R.id.Button05).setOnClickListener(this);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.Button01:
String urlToBeSend = " http://google.com";
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB);
fragmentB.b_updateText(urlToBeSend);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button02:
String urlToBeSend2 = " http://facebook.com";
String TabOfFragmentB2 = ((MainActivity)getActivity()).getTabFragmentB();
FragmentTab2 fragmentB2 = (FragmentTab2)getActivity().getSupportFragmentManager().findFragmentByTag(TabOfFragmentB2);
fragmentB2.b_updateText(urlToBeSend2);
Toast.makeText(getSherlockActivity(), "url to be send = " +urlToBeSend2, Toast.LENGTH_LONG).show();
viewPager.setCurrentItem(1);
break;
case R.id.Button03:
viewPager.setCurrentItem(1);
break;
case R.id.Button04:
viewPager.setCurrentItem(1);
break;
case R.id.Button05:
viewPager.setCurrentItem(1);
break;
default:
break;
}
}
}
For My FragmentTab2:
public class FragmentTab2 extends SherlockFragment {
private static WebView webview;
private ProgressBar progress;
String homeUrl="http://new3gpmovies.com/";
private int urlIndex=0;
String a_url;
TextView b_received;
ViewPager viewpager;
public void b_updateText(String t){
b_received.setText(t);
a_url = t;
}
public FragmentTab2(){
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.webview, container, false);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
b_received = (TextView) view.findViewById(R.id.textView1);
ImageView backward = (ImageView) view.findViewById(R.id.backward);
ImageView forward = (ImageView) view.findViewById(R.id.forward);
backward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoBack()){
webview.goBack();
}
}
});
forward.setOnClickListener(new OnClickListener(){
public void onClick(View view){
if (webview.canGoForward()){
webview.goForward();
}
}
});
webview = (WebView) view.findViewById(R.id.webView1);
webview.setWebChromeClient(new MyWebChromeClient());
webview.setWebViewClient(new MyWebViewClient());
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
progress = (ProgressBar) view.findViewById(R.id.progressBar1);
progress.setMax(100);
if (a_url != null){
webview.loadUrl(a_url);
}else if (a_url == null){
webview.loadUrl(homeUrl);
}
if (progress.getProgress() == 100){
FragmentTab2.this.progress.setProgress(0);
}
return view;
}
private class MyWebViewClient extends WebViewClient{
#SuppressLint({ "InlinedApi", "NewApi" })
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
boolean value = true;
if (url.endsWith(".3gp") || url.endsWith(".mp4")){
Intent downloadIntent = new Intent("com.nanoidea.download.services.IDownloadService");
downloadIntent.putExtra(MyIntents.TYPE, MyIntents.Types.ADD);
downloadIntent.putExtra(MyIntents.URL, Utils.url[urlIndex]);
getActivity().startService(downloadIntent);
urlIndex++;
if (urlIndex >= Utils.url.length) {
urlIndex = 0;
}
value=false;
}
if(value){
view.loadUrl(url);
}
return value;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
webview.loadUrl("file:///android_asset/failedPage.html");
}
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
if (url.endsWith("3gp")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".3gp");
}else if (url.endsWith(".mp4")){
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".mp4");
}
return filenameWithoutExtension;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
private class MyWebChromeClient extends WebChromeClient{
#Override
public void onProgressChanged(WebView view, int newProgress){
FragmentTab2.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
public void setValue(int progress){
this.progress.setProgress(progress);
}
public static boolean canGoBack(){
return webview.canGoBack();
}
public static void goBack(){
webview.goBack();
}
}
Question:
Why when i click on the link from the 1st tab the second tab doesn't change? even if the 2nd tab received the string url from the 1st tab? any idea? Please guide me.
Related
This is the MainActivity of my Tab View Layout
package com.nitol.aust.cse.austclassmanager;
public class ResultCheckActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private TabLayout t1;
private ViewPager vp1;
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navi_draw_result);
t1 = (TabLayout) findViewById(R.id.tab1);
vp1 = (ViewPager) findViewById(R.id.ViewPager1);
setUpMyViewPager(vp1);
t1.setupWithViewPager(vp1);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout) ;
navigationView = (NavigationView) findViewById(R.id.navigation_view);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle
(this,drawerLayout,toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(5).setChecked(true);
}
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> my_list = new ArrayList<Fragment>();
private final List<String> my_title = new ArrayList<String>();
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
return my_list.get(position);
}
#Override
public int getCount() {
return my_list.size();
}
void addMyFragment(Fragment f, String title){
my_list.add(f);
my_title.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return my_title.get(position);
}
}
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.home:
Intent intent0 = new Intent(ResultCheckActivity.this, MenuActivity.class);
startActivity(intent0);
finish();
break;
case R.id.routine:
Intent intent = new Intent(ResultCheckActivity.this, ClassRoutineActivity.class);
startActivity(intent);
finish();
break;
case R.id.cgpa:
Intent intent2 = new Intent(ResultCheckActivity.this, CgpaCalculator.class);
startActivity(intent2);
finish();
break;
case R.id.details:
Toast.makeText(getApplicationContext(),"Class Details",Toast.LENGTH_SHORT).show();
break;
case R.id.quiz:
Toast.makeText(getApplicationContext(),"Quiz Reminder",Toast.LENGTH_SHORT).show();
break;
case R.id.result:
break;
case R.id.profile:
Intent intent3 = new Intent(ResultCheckActivity.this, ProfileActivity.class);
startActivity(intent3);
finish();
break;
case R.id.about:
Toast.makeText(getApplicationContext(),"About",Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Intent intent4 = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent4);
finish();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tool,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.tool_settings){
Intent intent = new Intent(ResultCheckActivity.this, Settings.class);
startActivity(intent);
}
else if(id == R.id.tool_about){
Toast.makeText(getApplicationContext(),"This is About !", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
And this is my those tabs where i want to add refresh feature
void setUpMyViewPager(ViewPager vp){
ViewPagerAdapter viewPagerAdapter = new
ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addMyFragment(new WebViewEvents(),"News & Events");
viewPagerAdapter.addMyFragment(new WebViewAcademic(),"Academic Calendar");
viewPagerAdapter.addMyFragment(new WebViewTheory(),"Theory Results");
viewPagerAdapter.addMyFragment(new WebViewLab(),"Lab Results");
viewPagerAdapter.addMyFragment(new WebViewTeacher(),"Faculty Members");
vp.setAdapter(viewPagerAdapter);
}
Now suppose i want to add refresh on "WebViewEvents" class. The class is given below
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment {
View v;
WebView wb4;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
return v;
}
}
I found some instructions here but maximum of those was said that i have to #Override onRefresh() method...but i declared my class as a non activity class. so in a non activity class , i can not override a method. that's why i am not finding my solutions...
You just need to read docs on SwipeRefreshLayout
First, add SwipeRefreshLayout to your activity layout:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swiperefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
// here is your content
</android.support.v4.widget.SwipeRefreshLayout>
Then find instance of swipe refresh layout in your activity:
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
And set refresh listener in which trigger your update method
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
mSwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
myUpdateOperation();
}
}
);
For more information read docs, link in the beginning of the answer.
Also you might look at google samples:
SwipeRefreshLayoutBasic
SwipeRefreshListFragment
List of all google samples you can find here
Hope it helps
Finally this is worked for me
package com.nitol.aust.cse.austclassmanager;
public class WebViewEvents extends Fragment{
View v;
WebView wb4;
SwipeRefreshLayout mySwipeRefreshLayout;
private String currentUrl = "http://aust.edu/news_events.htm";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.webview_event, container,false);
mySwipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swiperefresh);
wb4 = (WebView) v.findViewById(R.id.webView_event);
wb4.setInitialScale(1);
wb4.getSettings().setJavaScriptEnabled(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wb4.setScrollbarFadingEnabled(false);
wb4.loadUrl(currentUrl);
wb4.setWebViewClient(new WebViewClient());
wb4.getSettings().setBuiltInZoomControls(true);
wb4.getSettings().setUseWideViewPort(true);
wb4.getSettings().setLoadWithOverviewMode(true);
wb4.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
wb4.setWebViewClient(new MyWebViewClient());
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
return v;
}
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
}
I added this override method inside my class
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
wb4.loadUrl(currentUrl);
}
}
);
Then added this to stop the refreshing animation
public class MyWebViewClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
mySwipeRefreshLayout.setRefreshing(false);
currentUrl = url;
super.onPageFinished(view, url);
}
}
Don't forget to add the instance of the last stopping animation impliment
wb4.setWebViewClient(new MyWebViewClient());
I have webview code in oncreate and onOptionsItemSelected which works properly as shown below.(this is my old code working as required)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState)
{ mwebView = (WebView) findViewById(R.id.pdf_web_view);
WebSettings settings = mwebView.getSettings();
settings.setJavaScriptEnabled(true);
mwebView.setWebChromeClient(new WebChromeClient());
mwebView.loadUrl("file://" + getFilesDir() + "/index.html");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_gotopage:
LayoutInflater layoutInflater = LayoutInflater.from(this);
View input_dialogView = layoutInflater.inflate(
R.layout.gotopage_dialogbox, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter the page number");
alert.setView(input_dialogView);
final EditText input = (EditText) input_dialogView
.findViewById(R.id.pagenum_edit);
input.requestFocus();
input.setTextColor(Color.BLACK);
alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String pg_num = input.getText().toString();
if (pg_num.equals("")) {
input.setError("Page number Required");
} else {
mwebView.loadUrl("javascript:onGotoPage("
+ pg_num + ")");
}
}
});
alert.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
// create an alert dialog
AlertDialog alert1 = alert.create();
alert1.show();
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
I want to convert this code to slide pages using ViewPager. So i have the code like this(My new code) :
MainActivity.java
public class Mainactivity extends AppCompatActivity {
private int NUM_PAGES=10;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_webview);
mPager = (ViewPager) findViewById(R.id.pdf_view_pager);
mPagerAdapter = new
ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new SlideFragment().create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
SlideFragment.java
public class SlideFragment extends Fragment {
private static final String ARG_PAGE = "page";
private int mPageNumber;
private WebView mwebView;
public static SlideFragment create(int pageNumber) {
SlideFragment fragment = new SlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.pdf_fragment_webview, container, false);
mwebView = (WebView) findViewById(R.id.pdf_web_view);
WebSettings settings = mwebView.getSettings();
settings.setJavaScriptEnabled(true);
mwebView.setWebChromeClient(new WebChromeClient());
mwebView.loadUrl("file://" + getFilesDir() + "/index.html");
mwebView.loadUrl("javascript:onGotoPage("
+ pg_num + ")");
}
}
The webview.loadURL only works first time, it doesn't work second time. But when it is inside onOptionsItemSelected method, it works fine.
I have tried all the solutions from WebView loadUrl works only once
Also tried onPageFinished and evaluate function.
But none worked in my case.I am not able to figure out what is wrong.
I think there is a race condition, between the html page loading and the javascript function running.
Would suggest you first load the html page, then in the onPageFinished callback run the javascript.
Also, when running javascript code on webview, you should use evaluateJavascript method.
Hope this helps.
I've seen a lot of examples for back button in webview. However, I have a tab layout using fragments and viewpager. I have seen an example that has an activity, but has an inner fragment class and the back button works. However, when I tried that, I got a lot of errors in my TabsPagerAdapter. If anyone has any idea how to do the code for the back button please tell me.
TabFour
public class TabFour extends Fragment {
static WebView webView;
String myBlogAddr = "http://192.168.1.75/Treasuria-v2/";
String myUrl;
Button map;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_tab_four, container, false);
webView= (WebView)rootView.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
String title = "Quezon City Guide";
String desc = "Your Number One City Guide!";
String image = "http://s22.postimg.org/5t4qidqpt/launcher114x114.png";
myBlogAddr ="http://www.facebook.com/sharer.php?m2w&s=100&p[title]="+title+"&p[summary]="+desc+"&p[url]=http://www.sample.com&p[images][0]="+image;
if(myUrl == null){
myUrl = myBlogAddr;
}
webView.loadUrl(myUrl);
Log.i("URL", myBlogAddr);
webView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
});
map = (Button) rootView.findViewById(R.id.buttonMap);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
});
return rootView;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
myUrl = url;
view.loadUrl(url);
return true;
}
}
public void onBackPressed() {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
public void OnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getActivity().getActionBar().setSelectedNavigationItem(1);
map = (Button) rootView.findViewById(R.id.buttonMap);
map.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getActionBar().setSelectedNavigationItem(2);
}
});
}
}
MainActivity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
public static FragmentManager fragmentManager;
public ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private Integer[] Icons = {R.drawable.homeg,R.drawable.placesg, R.drawable.mapg, R.drawable.reviewg,R.drawable.fbg};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (Integer tab_icon : Icons) {
actionBar.addTab(actionBar.newTab().setIcon(tab_icon)
.setTabListener(this));
}
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.synergy88studios.quezoncityguide",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
I want to detach/attach my fragments, but how to set, that fragment not recreate, after I attach.
In fragment I have WebView; when I select and unselect tabs, webview load startpage.
There is my code:
public class MainActivity extends Activity implements OnClickListener, OnMenuItemClickListener {
ActionBar bar;
View v;
public static TextView tilt;
LayoutInflater inflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
onAddTab();
View v=getLayoutInflater().inflate(R.layout.action_bar, null);
ImageButton im = (ImageButton)v.findViewById(R.id.tab_toggle);
im.setOnClickListener(this);
getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_layout));
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(v);
onToggleTabs();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.tab_toggle:
onAddTab();
break;
}
}
public void onAddTab() {
final ActionBar bar = getActionBar();
View v=getLayoutInflater().inflate(R.layout.layout_tab, null);
tilt = (TextView)v.findViewById(R.id.tit_le);
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
v.setLayoutParams(lp);
closetab = (ImageButton)v.findViewById(R.id.close);
closetab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onRemoveTab();
}
});
bar.addTab(bar.newTab()
.setCustomView(v)
.setTabListener(new TabListener<Web>(this, "Tag A", Web.class)));
}
public void onRemoveTab() {
final ActionBar bar = getActionBar();
Tab tab = bar.getSelectedTab();
bar.removeTab(tab);
}
public void onToggleTabs() {
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void onRemoveAllTabs(View v) {
getActionBar().removeAllTabs();
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener{
private final Activity myActivity;
private final String myTag;
private final Class<T> myClass;
public TabListener(Activity activity, String tag, Class<T> cls) {
myActivity = activity;
myTag = tag;
myClass = cls;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
// Check if the fragment is already initialized
if (myFragment == null) {
// If not, instantiate and add it to the activity
myFragment = Fragment.instantiate(myActivity, myClass.getName());
ft.add(R.id.fragment0, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(myFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);
if (myFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(myFragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
There is Fragment:
public class Web extends Fragment implements OnLongClickListener, OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
c=this.getActivity();
v = inflater.inflate(R.layout.activity_main, container, false);
return v;
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
wv = (WebView)v.findViewById(R.id.wv);
wv.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int progress) {
// TODO Auto-generated method stub
super.onProgressChanged(view, progress);
if(progress < 100 && pr.getVisibility() == ProgressBar.GONE){
pr.setVisibility(ProgressBar.VISIBLE);
}
pr.setProgress(progress);
if(progress == 100) {
pr.setVisibility(ProgressBar.GONE);
}
}
});
wv.setWebViewClient(new MyWebViewClient());
wv.loadUrl("http://www.google.com");
wv.setOnLongClickListener(this);}
Try setRetainInstance(boolean)
Also check this posts:
Android fragments setRetainInstance(true) not works (Android support library)
Fragment setRetainInstance not works (Android support lib)
Understanding Fragment's setRetainInstance(boolean)
I have an EditText view in my MainActivity that the user can input a url. This MainActivity also contains a fragment which will hold a WebView.
I have it set up so that when the fragment is displayed the url will load in the WebView. However I don't know how I can pass the String to the Fragment?
Below is the Main Activity code:
public class MainActivity extends FragmentActivity {
Button goBtn;
EditText urlInput;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
goBtn = (Button)findViewById(R.id.button1);
urlInput = (EditText)findViewById(R.id.editText1);
goBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
url = "http://"+urlInput.getText().toString(); //THIS TO FRAGMENT!
Toast.makeText(v.getContext(), "Search:" + url, Toast.LENGTH_SHORT).show();
}
});
and this is the fragment code:
WebView webDisplay;
String url;
AsyncHttpClient client;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag1_layout, container, false);
urlDisplay = (TextView)v.findViewById(R.id.textView1);
webDisplay = (WebView)v.findViewById(R.id.webView1);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//url = "http://"+this.getActivity() ???
client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
Toast.makeText(getActivity(), "Success!", Toast.LENGTH_SHORT).show();
webDisplay.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}});
webDisplay.loadUrl(url);
}
});
The value I am concerned about it the String URL variable in MainActivity.java.
The transaction of the fragments is controlled by a class TabFragment.
public class TabFragment extends Fragment {
private static final int TAB1_STATE = 0x1;
private static final int TAB2_STATE = 0x2;
private int mTabState;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_tab, container, false);
//References to buttons in layout file
Button tabBtn1 = (Button)v.findViewById(R.id.tabBtn1);
Button tabBtn2 = (Button)v.findViewById(R.id.tabBtn2);
//add listener to buttons
tabBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Action to perform when Tab 1 clicked...
goToTab1View();
}
});
tabBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Action to perform when Tab 2 clicked...
goToTab2View();
}
});
return v;
}
//Tab action functions.
protected void goToTab1View() {
if(mTabState != TAB1_STATE){
mTabState = TAB1_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab1());
ft.commit();
}
}
}
protected void goToTab2View() {
if(mTabState != TAB2_STATE){
mTabState = TAB2_STATE;
FragmentManager fm = getFragmentManager();
if(fm!= null){
//Perform fragment transaction
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new FragTab2());
ft.commit();
}
}
}
Or create Bundle and set it using method fragment.setArguments(myBundle);
This answer is in case the fragment already exists
You can define a public method in your fragment. Something like:
public void setString(final String str) { //... }
After that make your activity to implement OnClickListener interfave. And when the button is pressed just type something like that:
public void onClick(View view) {
// Form url...
((YourWebViewFragment) getFragmentManager().findFragmentById(fragments_id)).setString(url);
}