I'm new to android studio and I'm trying to remove a button from my videos app
I have 4 buttons in my app Android : Recent,Featured,Popular,Random and Live.
I would like to delete the Live button, but I am not able to
If necessary I can take a screenshot of my android studio.
I don't necessarily need to remove the button if I have another way to just hide it, that would be a big help too
I followed my code:
If necessary I can take a screenshot of my android studio.
package com.app.materialvideo.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.duolingo.open.rtlviewpager.RtlViewPager;
import com.app.materialvideo.Config;
import com.app.materialvideo.R;
import com.app.materialvideo.utils.CustomTabLayout;
import com.app.materialvideo.utils.SharedPref;
import static com.app.materialvideo.utils.Constant.FILTER_LIVE;
import static com.app.materialvideo.utils.Constant.FILTER_video;
import static com.app.materialvideo.utils.Constant.ORDER_FEATURED;
import static com.app.materialvideo.utils.Constant.ORDER_LIVE;
import static com.app.materialvideo.utils.Constant.ORDER_POPULAR;
import static com.app.materialvideo.utils.Constant.ORDER_RANDOM;
import static com.app.materialvideo.utils.Constant.ORDER_RECENT;
public class FragmentTabLayout extends Fragment {
public RelativeLayout tab_background;
public CustomTabLayout smartTabLayout;
public ViewPager viewPager;
public RtlViewPager viewPagerRTL;
public int tab_count = 5;
SharedPref sharedPref;
View view;
public FragmentTabLayout() {
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (Config.ENABLE_RTL_MODE) {
view = inflater.inflate(R.layout.fragment_tab_layout_rtl, container, false);
} else {
view = inflater.inflate(R.layout.fragment_tab_layout, container, false);
}
sharedPref = new SharedPref(getActivity());
tab_background = view.findViewById(R.id.tab_background);
smartTabLayout = view.findViewById(R.id.tabs);
if (sharedPref.getIsDarkTheme()) {
tab_background.setBackgroundColor(getResources().getColor(R.color.colorToolbarDark));
smartTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccentDark));
} else {
tab_background.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
}
initViewPager();
return view;
}
public void initViewPager() {
if (Config.ENABLE_RTL_MODE) {
viewPagerRTL = view.findViewById(R.id.view_pager_rtl);
viewPagerRTL.setOffscreenPageLimit(tab_count);
viewPagerRTL.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), tab_count));
smartTabLayout.post(() -> smartTabLayout.setViewPager(viewPagerRTL));
} else {
viewPager = view.findViewById(R.id.view_pager);
viewPager.setOffscreenPageLimit(tab_count);
viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager(), tab_count));
smartTabLayout.post(() -> smartTabLayout.setViewPager(viewPager));
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int noOfItems;
public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
this.noOfItems = noOfItems;
}
#NonNull
#Override
public Fragment getItem(int position) {
if (position == 0) {
return Fragmentvideo.newInstance(ORDER_RECENT, FILTER_video);
} else if (position == 1) {
return Fragmentvideo.newInstance(ORDER_FEATURED, FILTER_video);
} else if (position == 2) {
return Fragmentvideo.newInstance(ORDER_POPULAR, FILTER_video);
} else if (position == 3) {
return Fragmentvideo.newInstance(ORDER_RANDOM, FILTER_video);
} {
return Fragmentvideo.newInstance(ORDER_LIVE, FILTER_LIVE);
}
}
#Override
public int getCount() {
return noOfItems;
}
#Override
public String getPageTitle(int position) {
if (position == 0) {
return getResources().getString(R.string.menu_recent);
} else if (position == 1) {
return getResources().getString(R.string.menu_featured);
} else if (position == 2) {
return getResources().getString(R.string.menu_popular);
} else if (position == 3) {
return getResources().getString(R.string.menu_random);
} {
return getResources().getString(R.string.menu_live);
}
}
}
}
From my understanding, you don't want to remove a classic button, but a Tab button used inside a TabLayout.
If you want to remove it , easiest way would be to remove the last condition in your if else statements that deal with displaying and handling this button.
From the code you posted should be
Here
{
return getResources().getString(R.string.menu_live);
}
and here, as i think these two deal with the "Live" button.
{
return Fragmentvideo.newInstance(ORDER_LIVE, FILTER_LIVE);
}
As well as reduce the value passed to the ViewPager Adapter "noOfItems" variable by 1. In your situation, I think the variable is "tabCount" and that should be set to 4 ( down from 5). I see it's used in many places and changing this should deal with all cases.
If hiding is also good, then this code should also work.
Just use it inside onCreateView(). The code is in Kotlin and works on a default TabLayout, but i am not sure if it will work as i see you use a custom one.
tabLayout?.getTabAt(4)?.view?.visibility = View.GONE
You need to pass the index of the tab you want to hide, so in your case, you have 5 tabs, so the index is 4.
If you know id of the button.
view.findViewById(R.id.btn_firs).setVisibility(View.GONE);
Related
I want to add intent in sliding view pager. As I click different pages of the sliding view pager, a different activity must be called but I can't find the solution.
I have added image text and description in the view pager and a button is there in the layout
I think this would involve the use of page selected but earlier when I used onpageselected by using the position it opens up the page even if we are not clicking but I want to use intent here.
Adapterclass
package com.android.msahakyan.expandablenavigationdrawer.adapter;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.msahakyan.expandablenavigationdrawer.R;
import com.android.msahakyan.expandablenavigationdrawer.fragment.CardAdapter;
import com.android.msahakyan.expandablenavigationdrawer.fragment.CardItemString;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tanis on 21-06-2018.
*/
public class CardPagerAdapterS extends PagerAdapter implements CardAdapter {
private List<CardView> mViews;
private List<CardItemString> mData;
private float mBaseElevation;
public CardPagerAdapterS() {
mData = new ArrayList<>();
mViews = new ArrayList<>();
}
public void addCardItemS(CardItemString item) {
mViews.add(null);
mData.add(item);
}
public float getBaseElevation() {
return mBaseElevation;
}
#Override
public CardView getCardViewAt(int position) {
return mViews.get(position);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
mViews.set(position, cardView);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
mViews.set(position, null);
}
private void bind(CardItemString item, View view) {
TextView titleTextView = (TextView) view.findViewById(R.id.titleTextView);
TextView contentTextView = (TextView) view.findViewById( R.id.contentTextView);
ImageView imageView=(ImageView) view.findViewById( R.id.image12 ) ;
titleTextView.setText(item.getTitle());
contentTextView.setText(item.getText());
imageView.setImageResource( item.getImages() );
}
}
FragmentAction
package com.android.msahakyan.expandablenavigationdrawer.fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
//import android.support.v7.widget.LinearLayoutManager;
//import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.msahakyan.expandablenavigationdrawer.R;
import com.android.msahakyan.expandablenavigationdrawer.Registration;
import com.android.msahakyan.expandablenavigationdrawer.adapter.CardPagerAdapterS;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import in.goodiebag.carouselpicker.CarouselPicker;
import technolifestyle.com.imageslider.FlipperLayout;
import technolifestyle.com.imageslider.FlipperView;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentAction#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentAction extends Fragment {
ViewPager mViewPager;
CardPagerAdapterS mCardAdapter;
ShadowTransformer mCardShadowTransformer;
private Context context;
ViewPager viewPager;
String titlesText [] = {" Website Design", " Digital Marketing", " Domain Registration", "Graphics Design", " Mobile Apps", " Server Hosting",
" Software Development", " Content Marketing", " Security (SSl)"};
String detailsArray [] = {
"Your website is your digital home. We create, design, redesign, develop, improvise, and implement. We make beautiful websites",
"We help your business reach potential customers on every possible digital device through all possible media channels ",
"To launch your website the first thing you need is the domain name. You can choose your domain name with us here ",
"We generate creative solutions and can create a wide range of graphic for your clients which match their business ",
"We are mobile. And we make you mobile. We make responsive websites and mobile apps which compliment your business ",
"When you are hosting your website in the India you will benefit from a higher ping rate and lowest latency ",
"Our team is competent at coding web apps with keen attention to detail & intuitive functionality that is high on design & creativity",
"Content is the heart of your digital presence. We create the right content with the right focus for your business",
"Secure your site with the world's leading provider of online security and get these exclusive features at no added cost",
};
int[] images = {R.drawable.website_design, R.drawable.digita,R.drawable.domain_registration,R.drawable.graphic,
R.drawable.mob,R.drawable.server,R.drawable.software_development,R.drawable.ontent,R.drawable.ssl};
private static final String KEY_MOVIE_TITLE = "key_title";
public FragmentAction() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment.
*
* #return A new instance of fragment FragmentAction.
*/
public static FragmentAction newInstance(String movieTitle) {
FragmentAction fragmentAction = new FragmentAction();
Bundle args = new Bundle();
args.putString(KEY_MOVIE_TITLE, movieTitle);
fragmentAction.setArguments(args);
return fragmentAction;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_action,container,false);
TextView txt = (TextView)v.findViewById( R.id.textView12 );
txt.setText("\u25BA Creative & Dedicated Team");
TextView txt1 = (TextView)v.findViewById( R.id.textView13 );
txt1.setText("\u25BA Affordable Cost");
TextView txt2 = (TextView)v.findViewById( R.id.textView14 );
txt2.setText("\u25BA Maintain Long Relationship");
TextView txt3 = (TextView)v.findViewById( R.id.textView15 );
txt3.setText("\u25BA Timely Deliverly ");
context = this.getContext();
mViewPager = (ViewPager)v.findViewById(R.id.viewpager1);
mCardAdapter = new CardPagerAdapterS();
for (int i=0; i<titlesText.length; i++){
mCardAdapter.addCardItemS(new CardItemString( titlesText[i], detailsArray[i],images[i]));
}
mCardShadowTransformer = new ShadowTransformer(mViewPager, mCardAdapter);
mViewPager.setAdapter(mCardAdapter);
mViewPager.setPageTransformer(false, mCardShadowTransformer);
mViewPager.setOffscreenPageLimit(3);
viewPager = (ViewPager)v.findViewById( R.id.viewpager );
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter( this.getContext() );
viewPager.setAdapter( viewPagerAdapter );
Timer timer = new Timer( );
timer.scheduleAtFixedRate( new Mytime(),2000,4000 );
FloatingActionButton floatingActionButton = (FloatingActionButton)v.findViewById( R.id.floatingActionButton );
floatingActionButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity( new Intent( getActivity(),Registration.class ) );
}
} );
return v;
}
public class Mytime extends TimerTask{
#Override
public void run() {
getActivity().runOnUiThread( new Runnable() {
#Override
public void run() {
if(viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem( 1 );
}
else if (viewPager.getCurrentItem()== 1){
viewPager.setCurrentItem( 2 );
}
else if (viewPager.getCurrentItem()== 2){
viewPager.setCurrentItem( 3 );
}
else if (viewPager.getCurrentItem()== 3){
viewPager.setCurrentItem( 4 );
}
else {
viewPager.setCurrentItem(0);
}
}
} );
}
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Drawable movieIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.webdesign, getContext().getTheme());
String movieTitle = getArguments().getString(KEY_MOVIE_TITLE);
}
}
first of all onPageSelected listener is not really good idea in this case, because it is invoked every time when viewpager' current position changes (it's good for setting toolbar title, for example).
You can add another collection for Activities which can be invoked in CardPagerAdapterS, for example:
....
private List<CardItemString> mData;
private List<Class<? extends Activity> mActivities;
and use them to create click listener in order to open activities:
#Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.adapter, container, false);
container.addView(view);
bind(mData.get(position), view);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
if (mBaseElevation == 0) {
mBaseElevation = cardView.getCardElevation();
}
cardView.setMaxCardElevation(mBaseElevation * MAX_ELEVATION_FACTOR);
cardView.setOnCLickListener(v-> {
context.startActivity(new Intent(context, mActivities.get(position));
});
mViews.set(position, cardView);
return view;
}
How do I solve this issue without using SuppressWarning("uncheckedcast"), this there any way to check the object before casting it or any other way to solve this issue.
The problem is inside onLoadFinished(). I am using the data for different datatypes as you can see, first as boolean and then List.
Thank you in advance.
package com.howaboutthis.satyaraj.wallpaper;
import android.support.v4.app.Fragment;
import android.support.v4.content.Loader;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.LoaderManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class FragmentChanging extends Fragment implements LoaderManager.LoaderCallbacks {
private ProgressDialog dialog;
public FragmentChanging(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
final View view =
inflater.inflate(R.layout.fragment_changing_wallpaper, container, false);
getLoaderMangaer.init(0,null,FragmentChanging.this);
return view;
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
if (id == 0 || id == 2){
dialog.setMessage("Loading Settings...");
dialog.show();
}
return new TestInternetLoader(getContext());
}
return null;
}
#Override
public void onLoadFinished(Loader loader, Object data) {
int id = loader.getId();
if (id == 0 || id == 2){
boolean check = (Boolean) data;
if (check)
if (dialog.isShowing()) dialog.dismiss();
}
else if(id == 3)
List<Bitmap> bitmaps = (List<Bitmap>) data; //Unchecked cast
}
#Override
public void onLoaderReset(Loader loader) {
}
}
You can get rid of the lint warning by using a LoaderManager.LoaderCallbacks<List<Bitmap>> . If you want to do so, you'll have to change (almost) every occurrence of Loader to Loader<List<Bitmap>>.
(An exception seems to be onLoaderReset(Loader loader))
Moreover, if you use a custom AsyncTaskLoader it would have to extend AsyncTaskLoader<List<Bitmap>>.
Then you can write
#Override
public void onLoadFinished(Loader<List<Bitmap>> loader, List<Bitmap> data) {
List<Bitmap> bitmaps = data;
}
EDIT
If the suggested approach is not possible because the type of data may vary you can check for the types you are going to handle like this:
if (data instanceof List<?>){
List temp = (List)data;
// do what's required for List data
// (if necessary do a type check on list elements)
if (tempList.size() > 0){
Object firstItem = tempList.get(0);
if (firstItem instanceof Bitmap){
// now you know that your Loader gave you a List with at least one Bitmap
List<Bitmap> bitmaps = new ArrayList<>();
for (Object item: tempList){
if (item instanceof Bitmap){
bitmaps.add((Bitmap) item);
}
}
}
}
}
else if (data instanceof Boolean){
boolean check = (Boolean) data;
if (check){
// handle Boolean data
}
}
I'm currently working in my own project of dental application, i would like to ask if how to pass a certain data from a custom dialog and show or add it to the target fragment?
Appreciate for any help.
This is the Custom Dialog Screenshot:
CustomDialog.java
package com.bloxofcode.multipletabs;
import android.app.Activity;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.bloxofcode.multipletabs.Tab1;
public class CustomDialog extends Dialog implements
View.OnClickListener {
public Activity c;
public CustomDialog d;
public Button yes, no;
ToggleButton btnGenderMale,btnGenderFemale;
Button btnCancel, btnAccept;
EditText eText;
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setBackgroundDrawableResource(android.R.drawable.dialog_holo_light_frame);
}
else{
getWindow().setBackgroundDrawableResource(android.R.drawable.alert_light_frame);
}
setContentView(R.layout.activity_dialog);
btnGenderFemale = (ToggleButton) findViewById(R.id.toggleButtonFemale);
btnGenderMale = (ToggleButton) findViewById(R.id.toggleButtonMale);
btnCancel = (Button) findViewById(R.id.btnCancel);
btnAccept = (Button) findViewById(R.id.btnAccept);
eText = (EditText) findViewById(R.id.editText);
btnGenderMale.setChecked(true);
btnGenderMale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonMale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonMale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonMale.isChecked()){
btnGenderMale.setEnabled(false);
btnGenderFemale.setEnabled(true);
btnGenderFemale.setChecked(false);
}else{
}
}
});
btnGenderFemale.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonFemale, boolean b) {
// Toast.makeText(getApplicationContext(),
// String.valueOf(buttonFemale.isChecked()), Toast.LENGTH_SHORT).show();
if(buttonFemale.isChecked()){
btnGenderMale.setEnabled(true);
btnGenderFemale.setEnabled(false);
btnGenderMale.setChecked(false);
}else{
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),"Sample",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
dismiss();
}
}
How to achieve this Expected Result:
Tab1.java
package com.bloxofcode.multipletabs;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import com.bloxofcode.multipletabs.database.DBOpenHelper;
import com.bloxofcode.multipletabs.database.NotesProvider;
/**
* A simple {#link Fragment} subclass.
*/
public class Tab1 extends Fragment {
private ImageButton imgButton;
private CustomDialog customDialog;
View v;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v =inflater.inflate(R.layout.tab_1,container,false);
imgButton = (ImageButton) v.findViewById(R.id.imageButton);
//Creating ImageButton
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getActivity(),"Hello Image Button!",Toast.LENGTH_LONG).show();
customDialog = new CustomDialog(getActivity());
customDialog.show();
}
});
press();
return v;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void press() {
insertNote("Juan Dela Cruz");
Cursor cursor = getActivity().getContentResolver().query(NotesProvider.CONTENT_URI,
DBOpenHelper.ALL_COLUMNS, null, null, null, null);
String[] from = {DBOpenHelper.NOTE_TEXT};
int[] to = {android.R.id.text1};
CursorAdapter cursorAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_1,cursor,from,to,0);
ListView list = (ListView) v.findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
}
private void insertNote(String noteText) {
ContentValues values = new ContentValues();
values.put(DBOpenHelper.NOTE_TEXT,noteText);
Uri noteUri =getActivity().getContentResolver().insert(NotesProvider.CONTENT_URI,values);
Log.d("MainActivity","Inserted note " + noteUri.getLastPathSegment());
}
}
ViewPagerAdapter.java
package com.bloxofcode.multipletabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class ViewPagerAdapter extends FragmentStatePagerAdapter{
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab1 tab1 = new Tab1();
return tab1;
}
else if(position == 1)
{
Tab2 tab2 = new Tab2();
return tab2;
}
else // As we are having 3 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab3 tab3 = new Tab3();
return tab3;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
TabsActivity.java
package com.bloxofcode.multipletabs;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TabsActivity extends AppCompatActivity {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Patient","Appointment","Backup"};
int Numboftabs =3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
// Creating The Toolbar and setting it as the Toolbar for the activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
//return ContextCompat.getColor(TabsActivity.this,R.color.tabsScrollColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(R.color.tabsScrollColor,TabsActivity.this.getTheme());
}else {
return getResources().getColor(R.color.tabsScrollColor);
}
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you'd like to keep things loosely coupled and structured, A fine rather alternative is to choose the EventBus . To see the usage see this Answer.
You can accomplish it using Interface.
YourInterface.java
public interface YourInterface{
void yourMethod(int data);
}
Use that Interface in your Dialog class:
public class CustomDialog extends Dialog implements
View.OnClickListener {
private YourInterface delegate;
....
public CustomDialog(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
delegate = (YourInterface) a;
}
}
In your Activity that holds fragment implement interface:
public class YourActivity extends AppCompatActivity implements YourInterface {
....
#Override
public void yourMethod(int data) {
fragment.receiverMethod(data);
}
}
Tab1.java
public class Tab1 extends Fragment {
public void receiverMethod(int data) {
// do what you want with received data
}
}
Now to use that simply call delegate.yourMethod(data) to pass it to fragment
You can use Broadcast Receiver in your onDismiss like below in your Dialog
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (onDismissListener != null) {
Intent intent = new Intent("DialogDismiss");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
onDismissListener.onDismiss(dialog);
}
}
and in your Fragment you can receive the broadcast
// In your Fragment do below
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Work Here
}
};
//In OnCreate
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver,
new IntentFilter("DialogDismiss"));
//onDestroy
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
If you get the view from the customDialog you can just access the fields normally with view.findViewById() from in your fragment class.
Put your data into budle as key-value pair and set bundle as an argument to fragment.
fragment.setArgument(bundle)
To get bundle in fragmen, call
Bundle bundle = getArgument() and get values from the bundle based on key.
You could return the String which was entered into the EditText by creating a setter and getter method within your Dialog class to return a String variable (e.g. editTextString) which you would assign a value to whenever the accept button is clicked.
Add your getter and setter methods to the Dialog class
private void setEditTextString() {
editTextString = eText.getText().toString()
}
public String getEditTextString() {
return editTextString;
}
Within your click listener for the accept button add the following line of code:
setEditTextString(eText.getText().toString());
Then all you need to do to return the value entered in the editText field in the Fragment class would be to call the public method within your Dialog class to return the string.
dialogClass.getEditTextValue()
having some trouble getting 2 buttons to work.
In the screenshot below, I'm making 2 buttons called NEXT & BACK. And these buttons allows the user to change it from Week 1 to Week 3. When they click NEXT and reach Week , I need the button to disable and not allow them to proceed further since its only a max of 3 weeks. Same thing goes for the BACK button and cycling thru and reaching Week 1. See below also for my code.
http://i.stack.imgur.com/fLazK.jpg
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
final String PREFS_NAME = "MyPrefs";
ViewPager viewPager;
String week1 = "1";
String week2 = "2";
String week3 = "3";
private int[] weekNumbers = {1, 2, 3};
int weekNumberCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Casting variables
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
//////// First startup screen after first time use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
Intent VirginBoot = new Intent(this, Begin_Program.class);
startActivity(VirginBoot);
// Record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).apply();
}
}
public void settingsButton(View view) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
}
public void NextWeek(View view) {
int weekCounter = 0;
TextView weekNumber = (TextView) findViewById(R.id.week_number_text);
ImageButton LastWeekButton = (ImageButton) findViewById(R.id.LastWeek);
ImageButton NextWeekButton = (ImageButton) findViewById(R.id.NextWeek);
switch (view.getId()) {
case R.id.NextWeek:
if (weekCounter < (weekNumbers.length) - 2) {
weekCounter++;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week3);
LastWeekButton.setClickable(true);
NextWeekButton.setClickable(false);
}
}
case R.id.LastWeek:
if (weekCounter > weekNumbers.length) {
weekCounter--;
weekNumber.setText(week2);
if (weekCounter == (weekNumbers.length) - 1) {
weekNumber.setText(week1);
NextWeekButton.setClickable(true);
LastWeekButton.setClickable(false);
}
}
break;
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new Day_1();
}
if (arg0 == 1) {
fragment = new Day_2();
}
if (arg0 == 2) {
fragment = new Day_3();
}
if (arg0 == 3) {
fragment = new Day_4();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
}
Maybe I'm looking in the wrong areas but I've tried the links below and they havent worked so far.
How to disable button click?
How to disable button as soon as its clicked
Click Limiting on <button>
First off, you should probably store your buttons as fields in your class instead of finding them each time your functions are called, finding them the first time in the activity onCreate() instead. Then, in the OnClick of your button, you can call setEnabled(false) on that button depending on whether the button should still be enabled.
i am looking for a second opinion. I have a class that extends the Fragment class and contains a ViewPager and MaterialTabs. I need to find a workaround on a problem and I would like to remove tabs from ViewPager and add just one (fragment too) and so on.
For instance, i start with two tabs and on an action i want to remove those tabs and add a new one and on a different action to re-add those two tabs.
Is this plain stupid or it has a shot? Thank you.
Below is my class that i will work on:
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
/**
*
*/
public class PuzzlesTabActivity extends Fragment implements MaterialTabListener {
public static int NUM_TABS = 2;
public static boolean currentlyRunning;
private MaterialTabHost tabHost;
private ViewPager pager;
private PuzzlesTabActivity.ViewPagerAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(layout.puzzle_tab_layout, container, false);
if (Utils.isNetworkAvailable(this.getActivity())) {
this.tabHost = (MaterialTabHost) rootView.findViewById(id.myTabHost);
this.pager = (ViewPager) rootView.findViewById(id.myPager);
try {
this.pager.setPadding(0, 5, 0, 0);
// init view pager
this.adapter = new PuzzlesTabActivity.ViewPagerAdapter(this.getActivity().getFragmentManager());
this.pager.setAdapter(this.adapter);
this.pager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
PuzzlesTabActivity.this.tabHost.setSelectedNavigationItem(position);
}
});
this.pager.setCurrentItem(0);
// add tabs
for (int i = 0; i < this.adapter.getCount(); i++) {
this.tabHost.addTab(this.tabHost.newTab().setText(this.adapter.getPageTitle(i)).setTabListener(this));
}
} catch (Exception e) {
Log.e(Constants.TAG, e.getMessage());
}
} else {
ActivityCompat.startActivity(this.getActivity(), new Intent(this.getActivity(), MainActivity.class), null);
}
return rootView;
}
#Override
public void onTabSelected(MaterialTab tab) {
this.pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
}
#Override
public void onTabUnselected(MaterialTab tab) {
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
switch (num) {
case 0:
PuzzlesFragment aFragment = new PuzzlesFragment();
return aFragment;
case 1:
FavFragment nFragment = new FavFragment();
return nFragment;
default:
return new PuzzlesFragment();
}
}
#Override
public int getCount() {
return PuzzlesTabActivity.NUM_TABS;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return PuzzlesTabActivity.this.getResources().getString(string.new_puzzles);
case 1:
return PuzzlesTabActivity.this.getResources().getString(string.fav_puzzles);
default:
return PuzzlesTabActivity.this.getResources().getString(string.new_puzzles);
}
}
}
public void onPause() {
super.onPause();
SharedPreferences prefs = this.getActivity().getSharedPreferences(Utils.PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", this.getClass().getName());
editor.commit();
}
#Override
public void onStart() {
super.onStart();
PuzzlesTabActivity.currentlyRunning = true;
}
#Override
public void onStop() {
PuzzlesTabActivity.currentlyRunning = false;
super.onStop();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
Yes, this is fine. ViewPager already does something like this in a normal use case. It works by creating the fragment to the left, the current fragment, and the fragment to the right, as you swipe (so only three exist at a time).
As for adding and removing the tabs, that is fine to do as well. Just make sure to handle swapping for the new tab's fragment in the ViewPager.