I have Activity that contains custom ActionBar and ViewPager with three tabs.
I am not able to read text from EditText inside tab when click on button in ActionBar.
EDITED:
Contains TABS...
public class TranAdd extends FragmentActivity...{
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
EditText et;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
et = (EditText) mViewPager.findViewById(R.id.editText);
//...reference null...
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
TextView textViewTitle = (TextView) mCustomView.findViewById(R.id.textViewTitle);
textViewTitle.setText("New Transaction");
ImageView imageViewOk = (ImageView) mCustomView.findViewById(R.id.imageViewOk);
imageViewOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String txt = et.getText().toString();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
FRAGMENT:
public class Fragment extends Fragment...{
...
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
}
Try calling setHasOptionsMenu(true) inside your onCreate() method of the Fragment (tab) which needs to interact with the ActionBar.
Related
How can I call a method from fragment activity when my method placed is the Activity?
public class PosMainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trx);
Bundle extras = getIntent().getExtras();
if (extras != null) {
response_message = extras.getString("RESPONSE_MESSAGE");
}
//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);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public void parseJsonResponse(String jsonResponse){
// I parses and adds the value to the text view or button here
try {
JSONObject ResponseHeaderObject = new JSONObject(responseData);
String UIHeader = ResponseHeaderObject.getString("HEADER");
//Set Header Display
headerTextView =(TextView) findViewById(R.id.headerTextView);
headerTextView.setText(UIHeader);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
parseJsonResponse(response_message);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//Switch to different layout accordingly
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.fragment_receipt, container, false);
break;
}
}
return rootView;
}
}
}
When I place the parseJsonResponse in onViewCreated() method - I get the following error:
non static field cannot be referenced from a static context android
parseJsonResponse() is in my Activity class and I cannot change that to static method.
What I can do in this case?
Solution:
Call method of Activity from fragment
((YourActivityName)getActivity()).addUserLineInfoFragment();
Caution: This may cause leak somethimes. Hence,
Call method of fragment from Activity
1. Create Interface
public interface OnButtonListener
{
void onButtonClick();
}
2. Init in Activity
protected OnButtonListener onActionButtonListener;
public void setOnButtonListener(OnButtonListener actionButtonListener)
{
this.onActionButtonListener = actionButtonListener;
}
3. In Activity, click event when this action need to perform
this.onActionButtonListener.onButtonClick();
4. Implement listener(OnButtonListener) in Fragment
#Override
public void onButtonClick(){}
5. In fragment onCreateView
((YourActivityName) getActivity()).setOnButtonListener(this);
Source: Refer This
I have an app with 3 tabs. A tab has a fragment with a button to go another view within the same tab. My implementation is simple. I have main_activity with view pager. Here is snippet of main_activity.xml.
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Below the MainActivity.java
public class MainActivity extends AppCompatActivity {
public SectionsPageAdapter mSectionPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
setupViewPager(mViewPager);
//Assigns the ViePager to TabLayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
//Defines the number of tabs by setting appropriate fragment and tab name.
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new FirsTab(),"TAB1");
adapter.addFragment(new SecondTab(),"TAB2");
adapter.addFragment(new ThirdTab(),"TAB3");
viewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
When I replace the FirstTab with FirsTabSubFragment with getChildFragmentManager() I get a "no view found" error.
java.lang.IllegalArgumentException: No view found for id 0x7f0d0073 (com.none.app:id/pager) for fragment FirsTabSubFragment{607b4a6 #0 id=0x7f0d0073}
Below the code for FirtTab.java
public class FirstTab extends Fragment{
private Button btnScan;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.scan_layout, container, false);
btnScan = (Button) view.findViewById(R.id.btnScan);
btnScan.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
getChildFragmentManager()
.beginTransaction()
.replace(R.id.pager, new FirsTabSubFragment())
.addToBackStack(null)
.commit();
}
});
return view;
}
A replacement with a getFragmentmanager() results in a empty view. Can anyone advice me on this topic?
On toolbar there is a button. When the button is clicked a dialog popup's. In the dialog there are 2 spinner and a Select button. I need to get the current selected items of spinner inside Fragment. How can i do it?
public class MainActivity extends AppCompatActivity {
//Toolbar
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
//Navigation Drawer
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
Spinner spinner1, spinner2;
Dialog dialog;
Button toolbarButton;
public String sp11;
public String sp22;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbarButton = (Button) findViewById(R.id.toolBarButton);
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
return false;
}
});
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new TimeTableFragment(), "MONDAY");
viewPagerAdapter.addFragments(new TimeTableFragment(), "TUESDAY");
viewPagerAdapter.addFragments(new TimeTableFragment(), "WEDNESDAY");
viewPagerAdapter.addFragments(new TimeTableFragment(), "THURSDAY");
viewPagerAdapter.addFragments(new TimeTableFragment(), "FRIDAY");
viewPagerAdapter.addFragments(new TimeTableFragment(), "SATURDAY");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
public void myDialogPopUp(View view)
{
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_design);
spinner1 = (Spinner) dialog.findViewById(R.id.spinner1);
MyCustAdapter adapter = new MyCustAdapter(MainActivity.this, getResources().getStringArray(R.array.sp1));
spinner1.setAdapter(adapter);
spinner2 = (Spinner) dialog.findViewById(R.id.spinner2);
adapter = new MyCustAdapter(MainActivity.this, getResources().getStringArray(R.array.sp2));
spinner2.setAdapter(adapter);
dialog.setCancelable(true);
dialog.show();
}
public void onButtonSelect(View view)
{
sp11 = spinner1.getSelectedItem().toString();
sp22 = spinner2.getSelectedItem().toString();
//Toast.makeText(MainActivity.this, sp11+"\n"+sp22, Toast.LENGTH_SHORT).show();
dialog.cancel();
toolbarButton.setText(sp11+"\t\t\t˅\n"+sp22);
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
}
public class TimeTableFragment extends Fragment {
public TimeTableFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Toast.makeText(getActivity(), "\nonCreateView", Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_time_table, container, false);
}
}
you can create your own dialog and extend Dialog.
then add a method in your dialog:
public void setIndex(int index) {
this.index = index;
}
and then in your activity:
dialog = new CustomDialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_design);
dialog.setCancelable(true);
dialog.setIndex(index);
dialog.show();
Create a method in your TimeTableFragment to get the two values.
public class TimeTableFragment extends Fragment {
public void spinnerSelection(String one,String two){
}
}
Now you need to get the current selected fragment from the view pager. For that use the following code.
TimeTableFragment ttFrag=(TimeTableFragment)viewPagerAdapter.instantiateItem(viewPager , currentPosition)
ttFrag.spinnerSelection("Spinner1","Spinner2");
Put this inside the Spinner item click event.
Current position can be obtained by using the following methods
viewPager.getCurrentItem()
or
viewPageListener = new PageListener();
viewPager.setOnPageChangeListener(viewPageListener);
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViewPager();
}
private void setupViewPager() {
// TODO Auto-generated method stub
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), FragmentPagerItems.with(this)
.add("Home", HomeFragment.class)
.add("Message", MessageFragment.class)
.add("My", MyFragment.class).create());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab);
final LayoutInflater inflater = LayoutInflater.from(viewPagerTab.getContext());
final Resources res = viewPagerTab.getContext().getResources();
viewPagerTab.setCustomTabView(new SmartTabLayout.TabProvider() {
#Override
public View createTabView(ViewGroup container, int position,PagerAdapter adapter) {
ImageView icon = (ImageView) inflater.inflate(R.layout.mainactivity_tab, container, false);
switch (position) {
case 0:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_home));
break;
case 1:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_message));
break;
case 2:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_my));
break;
default:
throw new IllegalStateException("Invalid position: "+ position);
}
return icon;
}
});
viewPagerTab.setViewPager(viewPager);
}
Here is the code in that three fragment
public class HomeFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView title = (TextView) rootView.findViewById(R.id.item_title);
title.setText("Home");
return rootView;
}
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
Log.d("Action bar", "Home");
ActionBar mActionBar= getActivity().getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mCustomView = mInflater.inflate(R.layout.actionbar_message, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
TextView title = (TextView) mCustomView.findViewById(R.id.actionbar_message_title);
title.setText("Home action bar");
}
}
They work on MessageFragment.class and MyFragment but not HomeFragment.
It will crash and ActionBar mActionBar = getActivity().getActionBar(); will return null and crash.
Why it only works on MessageFragment and MyFragment?
HomeFragment is the first fragment to show.
My idea: I will to use different custom action bar on different fragment.
Replace this line
ActionBar mActionBar = getActivity().getActionBar();
by this
ActionBar mActionBar=((ActionBarActivity) getActivity()).getSupportActionBar();
It's because you extended ActionBarActivity
The problem is that your fragment is not attached to an activity when setMenuVisibility is called. Therefore getActivity returns null.
I don't understand why you'd want to mess with this method in the first place. You can just modify the the action bar in your onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
{
TextView title = (TextView) rootView.findViewById(R.id.item_title);
title.setText("Home");
}
ActionBar mActionBar= getActivity().getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mCustomView = mInflater.inflate(R.layout.actionbar_message, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
TextView title = (TextView) mCustomView.findViewById(R.id.actionbar_message_title);
title.setText("Message action bar");
return rootView;
}
If really do need the use of that method, then you could try a simple null check:
if (visible && getActivity() != null) {
I god the solutions, put my code in setUserVisibleHint
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
}
}
I've been wrestling with this for quite a while now.
I switched from having a regular Activity to now using fragments (by users recommendations), but I've been getting the same issue.
I have 3 pages that are now 3 fragments inside of a ViewPager. I want the button with the id addSiteButton in the addSite fragment; when clicked, to scroll over to setCurrentItem(2).
Any help is appreciated! Here's my code.
The FragmentActivity
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int page) {
switch (page) {
case 0: return new settingFields();
case 1: return new addSite();
case 2: return new createSite();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
The class with the button
public class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (container == null) {
return null;
}
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
I feel like I'm going in circles and not getting the desired motion.
Thanks for the help!
Simply make the Fragment as a class inside the FragmentActivity and take out the variable shadowing in onCreateView() since your pager is a global variable.
public class fieldsActivity extends FragmentActivity {
private static final int NUMBER_OF_PAGES = 3;
ViewPager mPager;
MyFragmentPagerAdapter mMyFragmentPagerAdapter;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// to create a custom title bar for activity window
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.fields);
// use custom layout title bar
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.topbar);
mPager = (ViewPager) findViewById(R.id.fieldspager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyFragmentPagerAdapter);
mPager.setCurrentItem(1);
}
public static class addSite extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RelativeLayout mRelativeLayout = (RelativeLayout) inflater.inflate(R.layout.add_site, container, false);
//final ViewPager mPager = (ViewPager) mRelativeLayout.findViewById(R.id.fieldspager);
Button addSiteButton = (Button) mRelativeLayout.findViewById(R.id.addSiteButton);
addSiteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(2, true);
}
});
return mRelativeLayout;
}
}
}
Also consider using the #Override annotation whenever you override a method so you don't make mistakes and use proper naming conventions. Java classes start with a capital.