How to display a fragment without clicking on it - java

I have a Tablelayout with two tabs, in the code I wrote that the tabs were displayed when I clicked on them. Now it works like this: I open the activity and the fragments from the TabLayout are not displayed until I click on the title of the TabLayout header. How can I make it so that when I open the activity - fragment it is already visible?
public class DetailActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
ImageView onBackPressed;
Button subsButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
subsButton = findViewById(R.id.subsButton);
subsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (subsButton.getText().equals("Подписаться")) {
subsButton.setText("Отписаться");
subsButton.setBackgroundColor(subsButton.getContext().getResources().getColor(R.color.colorGrey));
} else if (subsButton.getText().equals("Отписаться")) {
subsButton.setText("Подписаться");
subsButton.setBackgroundColor(subsButton.getContext().getResources().getColor(R.color.colorPrimary));
}
}
});
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
onBackPressed = (ImageView) findViewById(R.id.onBackPressed);
tabLayout.selectTab(tabLayout.getTabAt(0));
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Chelsea");
tabLayout.addTab(firstTab);
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Manchester City");
tabLayout.addTab(secondTab);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FragmentHisOne();
break;
case 1:
fragment = new FragmentHisTwo();
break;
default:
fragment = new FragmentHisOne();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void onBackPressed(View view) {
Intent intent = new Intent(view.getContext(), MainActivity.class);
view.getContext().startActivity(intent);
}

You are selecting the tab without even adding it before.
tabLayout.selectTab(tabLayout.getTabAt(0)); Move this code after adding tabs.

The fact is that I did not create the default fragment in advance, before creating the TabLayout tabs. My solution:
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
ImageView onBackPressed;
Button subsButton;
Fragment fragment = null;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
subsButton = findViewById(R.id.subsButton);
subsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (subsButton.getText().equals("Подписаться")) {
subsButton.setText("Отписаться");
subsButton.setBackgroundColor(subsButton.getContext().getResources().getColor(R.color.colorGrey));
} else if (subsButton.getText().equals("Отписаться")) {
subsButton.setText("Подписаться");
subsButton.setBackgroundColor(subsButton.getContext().getResources().getColor(R.color.colorPrimary));
}
}
});
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
onBackPressed = (ImageView) findViewById(R.id.onBackPressed);
tabLayout.selectTab(tabLayout.getTabAt(0));
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Chelsea");
tabLayout.addTab(firstTab);
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Manchester City");
tabLayout.addTab(secondTab);
fragment = new FragmentHisOne();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.simpleFrameLayout, fragment);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FragmentHisOne();
break;
case 1:
fragment = new FragmentHisTwo();
break;
default:
fragment = new FragmentHisOne();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void onBackPressed(View view) {
Intent intent = new Intent(view.getContext(), MainActivity.class);
view.getContext().startActivity(intent);
}
public void subsButton(View view) {
//Button.setBackground
}

Related

Set Text of EditeText of Fragment from Activity

How can I set the text of an EditText of an Fragment from the Activity?
Here es the Activity code:
public class MainActivity extends AppCompatActivity
{
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
tabLayout = (TabLayout) findViewById(R.id.simpleTabLayout);
// Create a new Tab named "First"
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Personal"); // set the Text for the first Tab
tabLayout.addTab(firstTab); // add the tab at in the TabLayout
// Create a new Tab named "Second"
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Chat"); // set the Text for the second Tab
tabLayout.addTab(secondTab); // add the tab in the TabLayout
try {
Fragment fragment = null;
fragment = new FirstFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
try {
Fragment fragment = null;
switch (tab.getPosition()) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
catch (Exception e) {
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void connect(){
//set text of EditText of SecondFragment
}
}
I am looking for a solution to this problem:
I want to create a chat client and for that I need to update the EditText of a tab from time to time without the need to switch to that tab. I also need the content of that EditText not to be lost when switching tabs.
Just create a variable inside the main activity that you can update from the fragments. Since the activity's lifecycle doesn't change from one fragment to the other, you can then get the same value from the second fragment.
I hope this helps.
Assuming you don't want to use a ViewPager and a PagerAdapter (you don't need swiping between your tabs), this is what it should look like:
public class MainActivity extends AppCompatActivity
{
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
EditText editText;
FirstFragment firstFragment;
SecondFragment secondFragment;
private int selectedTabIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
simpleFrameLayout = findViewById(R.id.simpleFrameLayout);
tabLayout = findViewById(R.id.simpleTabLayout);
TabLayout.Tab firstTab = tabLayout.newTab();
firstTab.setText("Personal");
tabLayout.addTab(firstTab);
TabLayout.Tab secondTab = tabLayout.newTab();
secondTab.setText("Chat");
tabLayout.addTab(secondTab);
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
firstFragment = new FirstFragment();
secondFragment = new SecondFragment();
fm.beginTransaction()
.add(R.id.simpleFrameLayout, firstFragment, "firstFragment")
.add(R.id.simpleFrameLayout, secondFragment, "secondFragment");
.detach(secondFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
.commitNow();
} else {
firstFragment = (FirstFragment) fm.findFragmentByTag("firstFragment");
secondFragment = (SecondFragment) fm.findFragmentByTag("secondFragment");
this.selectedTabIndex = savedInstanceState.getInt("selectedTabIndex", 0);
// selectTab(selectedTabIndex); // you don't need this line
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
this.selectedTabIndex = tab.getPosition();
selectTab(selectedTabIndex);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void selectTab(int selectedTabIndex) {
FragmentManager fm = getSupportFragmentManager();
if (selectedTabIndex == 0) {
fm.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.detach(secondFragment)
.attach(firstFragment)
.commitAllowingStateLoss();
} else if(selectedTabIndex == 1) {
fm.beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.detach(firstFragment)
.attach(secondFragment)
.commitAllowingStateLoss();
}
}
public void connect(){
secondFragment.updateText("someText"); // this can run when secondFragment has no view!
}
}
Note: if you need to use more tabs, then you could use an array, but you'd still need to initialize / reinitialize as it is shown in this snippet.
A general answer based on your general question Make your edittext public static public static EditText editText;
Assign a value to it then call it like MainActivity.editText.setText(""); from any other class
`
Use this approach only if its absolutely necessary as it may lead to memory leaks since you will have to manually destroy/nullify your object after use

Why there is no default tab is appearing when i open my application? [duplicate]

This question already has answers here:
TabLayout tab selection
(29 answers)
Closed 3 years ago.
I just want to set "Tab1" as default tab in this app and for that i set true in this piece of code '
tabLayout.addTab(tabLayout.newTab().setText("Tab1"), true);but, this is not working.
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
Toolbar toolbar;
Fragment fragment;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tablayout);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("lalit kumar");
setSupportActionBar(toolbar);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"), true);
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.addOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
fragmentimplement(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
public void fragmentimplement(int position) {
switch (position) {
case 0:
fragment = new AFragment();
break;
case 1:
fragment = new BFragment();
break;
case 2:
fragment = new CFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.frame, fragment).commit();
}
}
Add the Below line into Your code end of the Oncreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tablayout);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("lalit kumar");
setSupportActionBar(toolbar);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
tabLayout.addTab(tabLayout.newTab().setText("Tab1"), true);
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
}
private void setCurrentTabFragment(int tabPosition)
{
switch (tabPosition)
{
case 0 :
replaceFragment(fragmentOne);
break;
case 1 :
replaceFragment(fragmentTwo);
break;
case 3 :
replaceFragment(fragmentTwo);
break;
}
}
public void replaceFragment(Fragment fragment) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
}

pass explicit intent from ViewPagerAdapter to fragment

I have a viewpager with two tabs, and a fragment for each. How do i send an intent string extra to say FragmentMathematics()? This isnt as straight forward as creating an intent with a putExtra and then calling strartActivity().
Here is my simple class.
public class StartActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private String check;
private PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout404);
tabLayout.addTab(tabLayout.newTab().setText("Mathematics"));
tabLayout.addTab(tabLayout.newTab().setText("Physics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
Intent intent = getIntent();
check = intent.getStringExtra("SELECTVALUE");
if("Mathematics".equalsIgnoreCase(check)){
selectPage(1);
} else {
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
void selectPage(int pageIndex){
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setScrollPosition(pageIndex,0f,true);
viewPager.setCurrentItem(pageIndex);
}
Thank you!
Use Bundle to pass data to fragment.
Bundle bundle = new Bundle();
bundle.putString("edttext", "Your Value");
// set Fragmentclass Arguments
FragmentMathematics fragobj = new FragmentMathematics();
fragobj.setArguments(bundle);
And In fragment OnCreate()
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String strtext = getArguments().getString("edttext");
}

Switching to first tab in tabbed activity not working properly in android

So I have a weird problem. Basically I have a Main activity with four buttons, each button opens a different tab (there is 4 tabs). Now If I click 4th button I go to the 4th fragment but then if I try clicking on the first tab in tabbed activity it doesn't do anything.
So I can't go to the first tab if I start from 2nd 3rd or 4th unless I click on any other tab first.
It's only the first tab that works like this which makes me think that maybe there's some value that should be changing on menu button click but doesn't?
Here's my TabsActivity onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
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);
//
int defaultValue = 5;
//int page = getIntent().getIntExtra("One", defaultValue);
mViewPager.setCurrentItem(getIntent().getIntExtra("One", defaultValue));
//
//
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager))
Also here's TabsActivity class that takes care of selecting fragments:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
tab1recipes tab1 = new tab1recipes();
return tab1;
case 1:
tab2timer tab2 = new tab2timer();
return tab2;
case 2:
tab3measure tab3 = new tab3measure();
return tab3;
case 3:
tab4substit tab4 = new tab4substit();
return tab4;
default:
return null;
}
}
Here's MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.recipesbtn);
Button btn2 = (Button) findViewById(R.id.timerbtn);
Button btn3 = (Button) findViewById(R.id.measurebtn);
Button btn4 = (Button) findViewById(R.id.subsbtn);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int page=0;
Intent intent = new Intent(MainActivity.this, TabsActivity.class);//startActivity();
intent.putExtra("One", page);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int page=1;
Intent intent = new Intent(MainActivity.this, TabsActivity.class);//startActivity();
intent.putExtra("One", page);
startActivity(intent);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int page=2;
Intent intent = new Intent(MainActivity.this, TabsActivity.class);//startActivity();
intent.putExtra("One", page);
startActivity(intent);
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int page=3;
Intent intent = new Intent(MainActivity.this, TabsActivity.class);//startActivity();
intent.putExtra("One", page);
startActivity(intent);
}
});
Okay I finally fixed it. Here's how (just in case someone needs it too):
I placed the
mViewPager.setCurrentItem(getIntent().getIntExtra("One", defaultValue));
after
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
and now I feel very stupid

Back Stack in fragments not working

I have a home activity in that I am replacing fragments as required.
In home activity I have main fragment, then from main fragment I am replacing a Transport fragment, from Transport fragment I am replacing TransportList Fragment.
Now as I press back from TransportList fragment I see the main fragment instead of Transport fragment.
I have added the fragments to backstack still its working like this.
Home activity
public class HomeActivity extends AppCompatActivity{
private boolean mBackPressCancelled = false;
private static final long BACK_PRESS_DELAY = 10000;
private long mBackPressTimestamp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = HomeActivity.this.getFragmentManager();
MainFragment fragment = new MainFragment();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment,"MAIN_FRAGMENT").commitAllowingStateLoss();
}
#Override
public void onBackPressed() {
// Do nothing if the back button is disabled.
if (!mBackPressCancelled) {
// Pop fragment if the back stack is not empty.
if (getFragmentManager().getBackStackEntryCount() > 0) {
mTxtTitle.setVisibility(View.GONE);
mLogo.setVisibility(View.VISIBLE);
super.onBackPressed();
}
else {
if (snackbar != null) {
snackbar.dismiss();
}
long currentTimestamp = System.currentTimeMillis();
if (currentTimestamp < mBackPressTimestamp + BACK_PRESS_DELAY) {
super.onBackPressed();
} else {
mBackPressTimestamp = currentTimestamp;
Toast.makeText(this,"press again",Toast.LENGTH_LONG).show();
}
}
}
}
}
Transport fragment :
mBtnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
TransportListFragment fragment1 = new TransportListFragment();
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.mycontainer, fragment1).addToBackStack("G").commit();
}
});
Whats going wrong here please help.Thank you.
Just remove the following lines when you add new Fragment to the BackStack:
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

Categories

Resources