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) {
}
}
Related
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.
I have problem with the custom actionbar and actionbar tabs for android 4.0.when my application run in the 4.4(in nexus 7.0 tabs)it works fine,but the problem with 4.0 device.the custom actionbar and tabbar are combined and it shown in the whole actionbar. like this
Class
package com.android.timeline;
#SuppressLint({ "SimpleDateFormat", "NewApi" })
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
public int width;
private ActionBar actionBar;
private TextView actionBarTitle;
private TabPagerAdapter TabAdapter;
ArrayList<Fragment> fragmentlist = new ArrayList<Fragment>();
private ViewPager Tab;
private String[] tabs = { "About", "Watch Next", "Related" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentlist.add(new AboutDetail());
fragmentlist.add(new WatchNextDetail());
fragmentlist.add(new RelatedDetail());
currentAboutDetail = fragmentlist.get(0);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager) findViewById(R.id.pager);
Tab.setOffscreenPageLimit(2);
pagerchangeListener();
setupActionBar();
}
private void pagerchangeListener() {
Tab.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
Tab.setAdapter(TabAdapter);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("mMyCurrentPosition", Tab.getCurrentItem());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mMyCurrentPosition = savedInstanceState.getInt("mMyCurrentPosition");
// where mMyCurrentPosition should be a public value in your activity.
}
private void setupActionBar() {
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
View cView = getLayoutInflater().inflate(R.layout.actionbartitle, null);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);
actionBarTitle = (TextView) cView.findViewById(R.id.timeline);
getActionBar().setIcon(R.drawable.log);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f16c81")));
actionBar.setCustomView(cView);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
final ImageView actionBarDropDownImg = (ImageView) cView
.findViewById(R.id.pageback);
final ImageView share = (ImageView) cView.findViewById(R.id.setting);
final ImageView font = (ImageView) cView.findViewById(R.id.font);
OnClickListener neww = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == actionBarDropDownImg) {
finish();
overridePendingTransition(R.anim.anim_left,R.anim.anim_right);
}
if (v == font) {
((AboutDetail) currentAboutDetail).fontIncreament();
}
}
};
actionBarDropDownImg.setOnClickListener(neww);
share.setOnClickListener(neww);
font.setOnClickListener(neww);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
}
public class TabPagerAdapter extends FragmentStatePagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int i) {
Log.e("LOG", "Position || " + i);
return fragmentlist.get(i);
}
#Override
public int getCount() {
return fragmentlist.size(); // No of Tabs
}
#Override
public void destroyItem(View container, int position, Object object) {
}
}
#Override
public void onTabSelected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
please help me ,thanks in advance.
I had same issues with landscape mode and I found the solution here:
http://andreimihu.com/blog/2013/10/17/android-always-embed-tabs-in-actionbar/
Basically, the writer wants the tab inside actionbar while you and I wants it outside. So, just change the method call to false (code from the above link, but a bit modified):
// This is where the magic happens!
public void forceTabs() {
try {
final ActionBar actionBar = getActionBar();
final Method setHasEmbeddedTabsMethod = actionBar.getClass()
.getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
setHasEmbeddedTabsMethod.setAccessible(true);
setHasEmbeddedTabsMethod.invoke(actionBar, false);
}
catch(final Exception e) {
// Handle issues as needed: log, warn user, fallback etc
// This error is safe to ignore, standard tabs will appear.
}
}
I am going to develop a android app in Android 4.0 like the below image.
I have to create these tabs dynamically, that dynamically call addTab() method and create tab bar dynamically. Is the ActionBarWithTab right for my requirement.?Guide me to the right way. Please provide tutorials.
EDIT 1: I need to load webview in the separate tab bar created in the ActionBar.
EIDT 2: For creating the tab bar using the TabHost, first i have created the ViewGroup ffor TabHost and added the tab bar items like the below code. In the tab bar items I have created the layout, inside the layout a webview and loaded the dynamic url into the tab bar item. Finally I have set the viewgroup as contentview();
sTabHost = new TabHost(context,null);
sTabHost.setLayoutParams(
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
TabWidget tabWidget = new TabWidget(context);
tabWidget.setId(android.R.id.tabs);
sTabHost.addView(tabWidget, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
FrameLayout frameLayout = new FrameLayout(context);
frameLayout.setId(android.R.id.tabcontent);
final float scale = context.getResources().getDisplayMetrics().density;
int paddingtop = (int) (64 * scale + 0.5f);
frameLayout.setPadding(0, paddingtop, 0, 0);
sTabHost.addView(frameLayout, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
sTabHost.setup();
Then I have added the tab items like the below.
public void addTabItem(final String url, String tabTitle, Drawable tabIcon)
{
TabSpec ts1 = sTabHost.newTabSpec(tabTitle);
if(tabTitle.equals(""))
{
int childcount=sTabHost.getChildCount();
tabTitle="Tab" + String.valueOf(childcount+1);
}
if(tabIcon==null)
ts1.setIndicator(tabTitle);
else
ts1.setIndicator(tabTitle,tabIcon);
ts1.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
LinearLayout panel = new LinearLayout(sActiveContext);
panel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
panel.setOrientation(LinearLayout.VERTICAL);
FrameLayout layout=new FrameLayout();
// Here I am creating the webview loaded with the url within the layout and placed into the above FrameLayout.
panel.addView(layout);
return panel;
}
});
sTabHost.addTab(ts1);
sTabHost.setOnTabChangedListener(this);
}
Now, how can I achieve this in actionbar like the image I have added.?
I have created the Action Bar with tabs like the below code.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tabA = actionBar.newTab();
tabA.setText("Tab A");
tabA.setTabListener(new TabListener<MyFragmentA>(this, "Tag A", MyFragmentA.class));
actionBar.addTab(tabA);
}
The TabListener class is as below.
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(android.R.id.content, myFragment, myTag);
} else {
// If it exists, simply attach it in order to show it
ft.show(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.hide(myFragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
The Fragment class is as below.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_c, container, false);
WebView webview = (WebView) myFragmentView.findViewById(R.id.webview);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setBuiltInZoomControls(false);
webview.getSettings().setSupportZoom(false);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl("http://jquerymobile.com/demos/1.2.1/");
return myFragmentView;
}
public class MyWebViewClient extends WebViewClient {
/* (non-Java doc)
* #see android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String)
*/
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp4"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
}
else {
return super.shouldOverrideUrlLoading(view, url);
}
}
}
In the above implementation, I have created the layout and separate fragment class. Instead of creating like this how can I achieve this without creating the xml layout and separate fragment class. That is like the code i have posted for TabHost tab bar.
EDIT 3: I have created the action bar and tab items like the below code.
public void addTabBar(Context context)
{
sActiveContext=context;
sActionBar = getActionBar();
sActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
public void addTabItem(final String url, String tabTitle)
{
Tab tab = sActionBar.newTab();
if(tabTitle.equals(""))
{
int childcount=sActionBar.getTabCount();
tabTitle="Tab" + String.valueOf(childcount+1);
}
tab.setText(tabTitle);
//Here I need to create the Layout with the webview and loaded into the created tab.
tab.setTabListener(this);
sActionBar.addTab(tab);
}
How can I achieve to load the webview with the given url to the specific tab.?
Action Bar with Fragments
Try this, this works fine..
In manifest file,
<uses-sdk
android:minSdkVersion="11"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="packageName.ActionBarFragmentActivity"
android:configChanges="orientation"
android:theme="#android:style/Theme.Holo.Light"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!--change packageName -->
ActionBarFragmentActivity.java
#SuppressLint("NewApi")
public class ActionBarFragmentActivity extends FragmentActivity implements TabListener{
private ActionBar actionBar=null;
private Fragment1 fragment1=null;
private Fragment2 fragment2=null;
private Fragment3 fragment3=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
actionBar=getActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setTag("first").setText("First").setTabListener(this));
actionBar.addTab(actionBar.newTab().setTag("second").setText("Second").setTabListener(this));
actionBar.addTab(actionBar.newTab().setTag("third").setText("Third").setTabListener(this));
fragment1=new Fragment1();
fragment2=new Fragment2();
fragment3=new Fragment3();
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment1);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment1).commit();
fragment1.onUpdateView();
}
else if(tab.getPosition()==1)
{
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment2).commit();
fragment2.onUpdateView();
}
else if(tab.getPosition()==2)
{
getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment3).commit();
fragment3.onUpdateView();
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
main_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"
android:orientation="vertical" >
</FrameLayout>
webview_layout.xml
<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/webView"
android:layout_height="match_parent" >
</WebView>
Fragment1.java
public class Fragment1 extends android.support.v4.app.Fragment{
private WebView webView=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.webview_layout, container, false);
webView=(WebView)view.findViewById(R.id.webView);
return view;
}
#Override
public void onStart()
{
super.onStart();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop()
{
super.onStop();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle bundle)
{
super.onActivityCreated(bundle);
onUpdateView();
}
public void onUpdateView()
{
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
"/Physician_2_37/DOC/stamos-5644-00#gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
}
}
Fragmet2.java
public class Fragment2 extends android.support.v4.app.Fragment{
private WebView webView=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.webview_layout, container, false);
webView=(WebView)view.findViewById(R.id.webView);
return view;
}
#Override
public void onStart()
{
super.onStart();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop()
{
super.onStop();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle bundle)
{
super.onActivityCreated(bundle);
}
public void onUpdateView()
{
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.google.co.in/");
}
}
Fragment3.java
public class Fragment3 extends android.support.v4.app.Fragment{
private WebView webView=null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.webview_layout, container, false);
webView=(WebView)view.findViewById(R.id.webView);
return view;
}
#Override
public void onStart()
{
super.onStart();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop()
{
super.onStop();
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle bundle)
{
super.onActivityCreated(bundle);
}
public void onUpdateView()
{
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.youtube.com/?gl=IN&tab=w1");
}
}
Edited-------------"Dynamic Layouts"-------------------
Activity:-
onCreate();
FrameLayout frameLayout=new FrameLayout(this);
setContentView(frameLayout);
frameLayout.setId(1111);
Fragment Transaction...
getSupportFragmentManager().beginTransaction().replace(1111,fragment1).commit();
Fragment:-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
webView=new WebView(getActivity());
webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
return webView;
}
Answer for Edit 3:-
Try this,
#SuppressLint("ValidFragment")
public class Sample extends FragmentActivity implements TabListener{
private ActionBar mActionBar=null;
private ArrayList<String> arrayList=null;
private LinearLayout linearLayout=null;
private WebView webView=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
linearLayout=new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
setContentView(linearLayout);
mActionBar=getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
webView=new WebView(this);
linearLayout.addView(webView);
arrayList=new ArrayList<String>();
addTab(0,"https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
"/Physician_2_37/DOC/stamos-5644-00#gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
addTab(1,"https://www.google.co.in");
addTab(2,"http://stackoverflow.com/questions/15964641/tab-bar-app-in-android-4-0/16009038?noredirect=1#comment22832140_16009038");
}
private void addTab(int position,String URL)
{
mActionBar.addTab(mActionBar.newTab().setTag("tab"+String.valueOf(position)).
setText("Tab "+String.valueOf(position)).setTabListener(this));
arrayList.add(URL);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
webView.getSettings().setJavaScriptEnabled(true);
for (int i = 0; i < arrayList.size(); i++) {
if(tab.getPosition()==i)
{
webView.loadUrl(arrayList.get(i));
System.out.println(arrayList.get(i));
break;
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
//if(webView!=null)
//linearLayout.removeView(webView);
}
}
I think This is useful for you, for handle Action Bar. Also visit this for uses of Action Bar. Example and detailed description here .
And the you can use Tab Host control for tabs inside of Fragment(Sub Tabs). When you need
sub tabs on a fragment, then use Layout for that Fragment as,
sub_tab_fragment.xml,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="fill_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="#+android:id/realtabcontent"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</TabHost>
</LinearLayout>
And then inside of fragment,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.sub_tab_fragment, container, false);
mTabHost=(TabHost)v.findViewById(android.R.id.tabhost);
return v;
}
#Override
public void onActivityCreated(Bundle bundle)
{
super.onActivityCreated(bundle);
mTabHost.setup();
View tabview = createTabView(mTabHost.getContext(), "First");
mTabHost.addTab(mTabHost.newTabSpec("First").setIndicator(tabview).setContent(R.id.realtabcontent));
View tabview1 = createTabView(mTabHost.getContext(), "Second");
mTabHost.addTab(mTabHost.newTabSpec("Second").setIndicator(tabview1).setContent(R.id.realtabcontent));
View tabview2 = createTabView(mTabHost.getContext(), "Third");
mTabHost.addTab(mTabHost.newTabSpec("Third").setIndicator(tabview2).setContent(R.id.realtabcontent));
View tabview3 = createTabView(mTabHost.getContext(), "Fourth");
mTabHost.addTab(mTabHost.newTabSpec("Fourth").setIndicator(tabview3).setContent(R.id.realtabcontent));
View tabview4 = createTabView(mTabHost.getContext(), "Fifth");
mTabHost.addTab(mTabHost.newTabSpec("Fifth").setIndicator(tabview4).setContent(R.id.realtabcontent));
mTabHost.setOnTabChangedListener(mTabListener);
}
Then you will implement/handle contents of tabs(Same method used in Action Bar).
Edited-----addTabItem(final String url, String tabTitle, Drawable tabIcon)*****
public void addTabItem(final String url, String tabTitle, Drawable tabIcon)
{
WebView webView=null;
TabSpec ts1 = sTabHost.newTabSpec(tabTitle);
if(tabTitle.equals(""))
{
int childcount=sTabHost.getChildCount();
tabTitle="Tab" + String.valueOf(childcount+1);
}
if(tabIcon==null)
ts1.setIndicator(tabTitle);
else
ts1.setIndicator(tabTitle,tabIcon);
ts1.setContent(new TabHost.TabContentFactory(){
public View createTabContent(String tag)
{
webView=new WebView(sActiveContext);
webView.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
return webView;
}
});
sTabHost.addTab(ts1);
sTabHost.setOnTabChangedListener(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
"/Physician_2_37/DOC/stamos-5644-00#gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
}
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);
}