Delay showing content in Fragment Pager Adapter - delay

I'm using FragmentPagerAdapter has 5 tabs.
In tab number 3 I'm showing data in listview from web service and it showing successfully.
When I swipe to tab 2, 4 and return to tab 3, the data is still showing in listview.
If I swipe to tab 1, 5 and return to tab 3, the data delay to appearing some seconds.
* In TabFragment class I'm calling AsyncTask class called "GetTopNotifications". like this coding:
public static class TabFragment extends Fragment
{
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle args = getArguments();
int position = args.getInt(ARG_OBJECT);
int tabLayout = 0;
switch (position)
{
case 0:
tabLayout = R.layout.tab1;
break;
case 1:
tabLayout = R.layout.tab2;
break;
case 2:
tabLayout = R.layout.tab3;
break;
case 3:
tabLayout = R.layout.tab4;
break;
case 4:
tabLayout = R.layout.tab5;
break;
}
View rootView = inflater.inflate(tabLayout, container, false);
if(position==2)
{
InitialTab3(rootView);
new GetTopNotifications(rootView);
}
return rootView;
}
}

Related

Switch from Activity to the recent fragment visited in BottomNavigationView

I am trying to make a social media app , Im using fragments within BottomNavigation (home - smart room - notifications - profile), And Im using a floating button to switch to "Add post" activity , Now Im having a problem with the back button , i want it to take me to the recent visited fragment but it always take me to the home fragment
here is my BottomNavigation activity code :
public class BottomNavigationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom_navigation);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_layout);
//setEnabled(false) for the 2nd index because we're using a floating button instead
bottomNav.setBackground(null);
bottomNav.getMenu().getItem(2).setEnabled(false);
bottomNav.setOnItemSelectedListener(navListener);
//start AddPostActivity class
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddPostActivity.class));
finish();
}
});
}
//Switch between fragments
public BottomNavigationView.OnItemSelectedListener navListener =
new BottomNavigationView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_sr:
selectedFragment = new SmartRoomFragment();
break;
case R.id.nav_notif:
selectedFragment = new NotificationsFragment();
break;
case R.id.nav_profile:
selectedFragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
I want the best solution to handle this problem , thanks in advance!

Going to Main Activity from fragment

I implemented a navigation drawer and had used fragments. Now i can switch to fragments from the drawer menu. But when i press back, my app closes from that fragment and don't know how to go back to the main activity.
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(id);
return true;
}
private void displaySelectedScreen(int id) {
Fragment frag = null;
switch (id) {
case R.id.trigger:
break;
case R.id.setup:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
frag = new SettingsF();
break;
case R.id.recordings:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#4E342E"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8D6E63")));
break;
case R.id.howto:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.about:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
case R.id.email_us:
if (android.os.Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.parseColor("#7B1FA2"));
}
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#8E24AA")));
break;
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, frag);
ft.addToBackStack(ft.getClass().getSimpleName()).commit();
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
And here is the setting fragment only:
public class SettingsF extends ListFragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_settings, container, false);
String[] datasource = {"Trusted Contacts", "Custom Text Set-Up"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.rowlayout, R.id.txtitems, datasource);
setListAdapter(adapter);
setRetainInstance(true);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Context Set-Up");
}
public void onListItemClick(ListView l, View view, int position, long id) {
ViewGroup viewGroup = (ViewGroup) view;
TextView tv = (TextView) viewGroup.findViewById(R.id.txtitems);
Toast.makeText(getActivity(), tv.getText().toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener( new View.OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//Already Used Intent, doesn't work
return true;
}
return false;
}
} );
super.onResume();
}
}
I updated the question. I already used addToBackStack(), then overrided the method onResume() but still the app terminates when pressing the back button.
I'm really that new to this, so don't misunderstand me what did i implemented throughout the codes.
Thanks In Advance
for Hardware backbutton
add this code in onResume method in fragment
//You need to add the following line
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener()
{
#Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
//here use intent to call mainActivity
return true;
}
return false;
}
} );
hope this will help you
Add this line after ft.replace():
ft.addToBackStack(null);
This line will make it so that each time you select an item from the navigation drawer, a history of fragments is built up. Then when you press the back button, you'll go back through the history. If you have no history items, the app will close.
A more sophisticated implementation might use a name argument (like "FragA" or "FragB") instead of null as the argument for addToBackStack(), and then check to see if your fragment already exists in the back stack instead of always opening a new one. That way if you went A->B->A->B->A->B you wouldn't have three copies of A and two copies of B in the history.

AppBar tabs on click listener

I have a tabbed activity with fragments.
The number of tabs is generate from the default code bellow:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 6;
}
}
I have add icons on my tabs with the code bellow:
private int[] tabIcons = {
R.drawable.web,
R.drawable.social,
R.drawable.contact,
R.drawable.partners,
R.drawable.exclusivevideo,
R.drawable.jobifyblack
};
And inside onCreate(Bundle savedInstanceState) i am using the code bellow:
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Add icons on tabs
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
tabLayout.getTabAt(5).setIcon(tabIcons[5]);
By default all tabs are generated inside AppBarLayout.
Now the only thing that i want is how to trigger a click on last tab to open a new activity and do not open fragment inside container.
I tried a lot of examples without any luck!
http://www.mkyong.com/android/android-tablayout-example/
Try this example if you are not looking this please comment

Change the selected tab background and text color of TabLayout

I want to change the selected tab background and text color from Java.
I created this activity from Android studio build in activity and make a little change for me.
My code is
public class BanglalinkInternetPack extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banglalink_internet_pack);
//getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f37022")));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
return new Montly_pack_bl();
case 1:
return new Daily_packs_bl();
case 2:
return new Weekly_pack_bl();
case 3:
return new Montly_pack_bl();
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Most Used";
case 1:
return "Daily";
case 2:
return "Weekly";
case 3:
return "Monthly";
}
return null;
}
}
}
Where do I need to change?
Use app:tabSelectedTextColor and app:tabTextColor:
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/blue"
app:tabSelectedTextColor="#color/blue"
app:tabTextColor="#color/black"
/>
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
// void setTabTextColors(int normalcolour, int selectedcolour)
tabLayout.setTabTextColors(-1,-256);
Use this method to change colour of your tab title , keep parameters same in case you dont want to change colour on selected and also check this
https://developer.android.com/reference/android/support/design/widget/TabLayout.html#setSelectedTabIndicatorColor(int)

How add custom dynamic layout in a dialog box?

i am new to android java programming. I am adding a custom dynamic layout to a dialog box. i have 2 classes , Mainactivity.java and Getval.java
The Mainactivity.java create a dialoge and Getval generates dynamic layout at run time.
Every thing works good but when it tried to call Getval.java's method, it gives an exception. here is the code of both classes.
The g.setval(); in Mainactivity.java cause problem.
:::::Mainactivity.java:::::
public class MainActivity extends Activity {
private Button button;
public Getval g=new Getval();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.buttonShowCustomDialog);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//set up dialog
g.setval();
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.attributewin);
dialog.setTitle("Attribute Window");
dialog.setCancelable(true);
dialog.show();
}
});
::::Getval::::
public class Getval extends Activity{
String names[]={"test","chaeck","kajsdhasj","dlasdig"};
String values[]={"test","chaeck","kajsdhasj","dlasdig"};
String test[]={"Attribut","Value"};
public void setval(){
TableLayout tl = (TableLayout) findViewById(R.id.tly);
Button b=new Button(this);
for (int i = 0; i < names.length; i++) {
//Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
//TextViews
TextView tv0 = new TextView(this);
tv0.setText(names[i]);
tv0.setMaxWidth(75);
TextView tv1 = new TextView(this);
tv1.setText(values[i]);
tv1.setMaxWidth(150);
View line = new View(this);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(Color.BLACK);
//Setting Views
tr.addView(tv0);
tr.addView(tv1);
tl.addView(tr);
tl.addView(line);
}
//Button Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
tr.setGravity(0x11);
b.setId(100);
b.setText("Return");
b.setGravity(0x11);
tr.addView(b);
tl.addView(tr);
}
}
Looking over this without seeing your xml or complete code (or exception that is thrown), I would be willing to guess that you are trying to inflate/modify a view (R.id.tly) from an activity other than the one where it was originally inflated from (MainActivity).
Generally speaking, you can't do this without doing some tricks with cross activity handlers or other methods. Perhaps change your code to inflate the views (R.id.tly) in MainActivity (and in your dialog if it is inside of R.layout.attributewin), do your processing in Getval, return them to MainActivity so it can populate the views.
But again, this is just a guess, since I don't see your xml or exception.

Resources