I have created tabbed activity with two tab (edittext in tab1,listview in tab2),and I pass data in tab1 to listview in tab2, how to set title for listview
please help
my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="store.exercise.com.store.MainActivity$PlaceholderFragment">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
fragment one:
public class FragmentOne extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_one, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
fragment two :
public class FragmentTwo extends Fragment {
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_two, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
}
protected void displayReceivedData(String message) {
arrayList.add(message);
adapter.notifyDataSetChanged();
}
}
my ViewPagerAdapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new FragmentOne();
} else if (position == 1) {
fragment = new FragmentTwo();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
if (position == 0) {
title = " مهمة جديدة ";
} else if (position == 1) {
title = " المهام ";
}
return title;
}
}
make sure you have the following on your activity_view.xml where you have your viewpager
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="#dimen/center_section_tab_bar_header_height"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
and in your activity class add the following line to setup the viewpager with the tab layout header
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(yourviewpager);
after which it sets up the header for your tabs as mentioned in your code
Related
Trying to use LeanbackTabLayout & LeanbackViewPager to create top navigation in my AndroidTv app, but somehow my rowsAdapter is null & crashes on setAdapter. When I debug, I see that the ListRow is not null. What am I doing wrong?
HomeActivity:
public class HomeActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
LeanbackTabLayout leanbackTabLayout = ActivityCompat.requireViewById(this, R.id.tablayout);
leanbackTabLayout.setFocusable(true);
LeanbackViewPager leanbackViewPager = ActivityCompat.requireViewById(this, R.id.viewpager);
TablayoutAdapter adapter = new TablayoutAdapter(getSupportFragmentManager(), 3);
leanbackViewPager.setAdapter(adapter);
leanbackTabLayout.setupWithViewPager(leanbackViewPager);
}
}
TablayoutAdapter:
public class TablayoutAdapter extends FragmentStatePagerAdapter {
int tabCount;
public TablayoutAdapter(#NonNull FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#NonNull
#Override
public Fragment getItem(int position) {
return new HomeFragment();
}
#Override
public int getCount() {
return tabCount;
}
}
HomeActivity xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeActivity">
<androidx.leanback.tab.LeanbackTabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:nextFocusDown="#id/viewpager"
/>
<androidx.leanback.tab.LeanbackViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
HomeFragment:
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListRowPresenter lrp = new ListRowPresenter();
final CardPresenter cardPresenter = new CardPresenter();
ArrayObjectAdapter rowsAdapter = new ArrayObjectAdapter(lrp);
for (int i = 0; i < 3; ++i) {
ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter);
listRowAdapter.add(new Navigation("Tab1"));
listRowAdapter.add(new Navigation("Tab2"));
listRowAdapter.add(new Navigation("Tab3"));
HeaderItem header = new HeaderItem(i, "Row " + i);
System.out.println(header);
System.out.println("hello");
rowsAdapter.add(new ListRow(header, listRowAdapter));
}
RowsSupportFragment rowsSupportFragment = (RowsSupportFragment) getChildFragmentManager().findFragmentById(R.id.row1);
System.out.println(rowsAdapter);
System.out.println("hello");
rowsSupportFragment.setAdapter(rowsAdapter);
}
}
HomeFragment xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/row1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
I have an xml layout file called fragment_about_sl.xml and the class associated to that called aboutSLFragment.java which is extended to fragment.java. Anyway all I want to do is make the toolbar transparent and overlay the image for this class only.I am new to android, so please help.
fragment_about_sl.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/aboutslscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.navigationdrawerfragments.aboutSLFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="250dp" />
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/viewPager"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
aboutSlFragment.java
public class aboutSLFragment extends Fragment{
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
TextView aboutsltext;
Button readmorebtn;
public aboutSLFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_sl, container,
false);
viewPager = (ViewPager) rootView .findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
aboutsltext=(TextView)rootView.findViewById(R.id.aboutsltext);
readmorebtn=(Button)rootView.findViewById(R.id.readmorebtn);
readmorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (readmorebtn.getText().toString().equalsIgnoreCase("Read More"))
{
aboutsltext.setMaxLines(Integer.MAX_VALUE);//your TextView
readmorebtn.setText("Read Less");
}
else
{
aboutsltext.setMaxLines(3);//your TextView
readmorebtn.setText("Read More");
}
}
});
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments
different titles
getActivity().setTitle("About Sri Lanka");
}
I want my app to be like this
You can do that in onResume of that fragment:
#Override
public void onResume() {
super.onResume();
AppCompatActivity activity = (AppCompatActivity) getActivity();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.hide();
}
I have a main Activity containing a parent Fragment, which in turn contains a child Fragment. I am trying to make a TextView in the child Fragment visible/invisible dynamically.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the Activity"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/parent_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_parent.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the parent fragment"
android:id="#+id/textView"/>
<FrameLayout
android:id="#+id/child_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
fragment_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This text belongs to the child fragment"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="But make this text visible dynamically!"
android:id="#+id/make_this_text_visible"
android:visibility="invisible"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String PARENT_TAG = "parent_tag";
private ParentFragment mParentFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
mParentFragment = ParentFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.parent_container, mParentFragment, PARENT_TAG).commit();
}
else {
mParentFragment = (ParentFragment) getSupportFragmentManager().findFragmentByTag(PARENT_TAG);
}
}
}
ParentFragment.java
public class ParentFragment extends Fragment {
public static final String CHILD_TAG = "child_tag";
private ChildFragment mChildFragment;
private List<Integer> mList;
public static ParentFragment newInstance() {
Bundle args = new Bundle();
ParentFragment fragment = new ParentFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
mList = new ArrayList<Integer>();
if (savedInstanceState == null) {
mChildFragment = ChildFragment.newInstance();
getChildFragmentManager().beginTransaction().replace(R.id.child_container, mChildFragment, CHILD_TAG).commit();
}
else {
mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentByTag(CHILD_TAG);
}
getChildFragmentManager().executePendingTransactions(); //doesn't seem to do anything!
doStuff();
return view;
}
void doStuff() {
mList.add(4); //pretend this is actually querying a database.
//for simplicity it just receives a single 4.
if (mList.size() > 0) { //the list is not empty, display the text!
mChildFragment.setTextVisible(); //error! the textivew of the child fragment is null right now
}
else {
mChildFragment.setTextInvisible(); //error! the textivew of the child fragment is null right now
}
}
}
ChildFragment.java
public class ChildFragment extends Fragment {
private TextView mTextView;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
return view;
}
public void setTextVisible() {
mTextView.setVisibility(View.VISIBLE);
}
public void setTextInvisible() {
mTextView.setVisibility(View.INVISIBLE);
}
}
How can I ensure that the child fragment is formed by the time I call doStuff() in the ParentFragment?
What I would do is keep the state of the text view visibility so it can be updated properly once the view has been created if it hasn't been already. Instead of separate methods for setTextVisible() and setTextInvisible have a single method setTextVisibile(boolean isVisible) and implement it as follows:
public class ChildFragment extends Fragment {
private TextView mTextView;
private boolean mIsTextVisible;
public static ChildFragment newInstance() {
Bundle args = new Bundle();
ChildFragment fragment = new ChildFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
setTextVisible(mIsTextVisible);
return view;
}
public void setTextVisible(boolean isVisible) {
mIsTextVisible = isVisible;
if(mTextView != null) {
mTextView.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
}
}
and then in the parent fragment you can call doStuff() without worrying about the current state of the views in the ChildFragment since mIsTextVisible is properly set. If the mTextView is null at the time setTextVisible() is called the visibility will still be properly set in onCreateView().
Just take care to save and restore the mIsTextVisible flag when the fragment is recreated such as when the device is rotated.
Alternative Answer Using A Callback
Using callbacks update the ParentFragment to implement
ChildFragment.OnViewCreatedListener and its method.
public class ParentFragment extends Fragment
implements ChildFragment.OnViewCreatedListener {
#Override
public void onViewCreated() {
doStuff();
}
}
And then in ChildFragment
public class ChildFragment extends Fragment {
public interface OnViewCreatedListener {
void onViewCreated();
}
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
mTextView = (TextView) view.findViewById(R.id.make_this_text_visible);
if(getParentFragment() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getParentFragment()).onViewCreated();
} else if (getActivity() instanceof OnViewCreatedListener) {
((OnViewCreatedListener) getActivity()).onViewCreated();
}
return view;
}
}
I'm trying to get a simple TabLayout with 3 tabs. Having follow different tutorials, my tab don't show up on the final result ( There is just 3 empty tab with no text ).
This how I try to add those tabs:
First the xml layout container the ViewPager (communitylayout)
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:padding="4dip"
android:layout_above="#+id/bottomcontent3"
android:gravity="center_horizontal"
android:background="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/comtabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
android:background="#android:color/white" />
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/compager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.design.widget.AppBarLayout>
The Tab xml (tabtext):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tabtext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="#color/tab_text_color"
/>
</RelativeLayout>
And finally the java class where I try to add those Tabs:
super.onSaveInstanceState(savedInstanceState);
view = inflater.inflate(R.layout.communitylayout, container, false); // communitylayout is the first xml I put, see above
Bundle data = getArguments();
MainActivity.addShapeAndBottom(inflater, view, "com", this);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.comtabs);
// add tabs
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
RelativeLayout layout1 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
RelativeLayout layout2 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
RelativeLayout layout3 = (RelativeLayout) inflater.inflate(R.layout.communitytablayout, container, false);
//tab is an array of Strings containing the Tab name
((TextView)layout1.findViewById(R.id.tabtext)).setText(tabs[0]);
((TextView)layout2.findViewById(R.id.tabtext)).setText(tabs[1]);
((TextView)layout3.findViewById(R.id.tabtext)).setText(tabs[2]);
tabLayout.getTabAt(0).setCustomView(layout1);
tabLayout.getTabAt(1).setCustomView(layout2);
tabLayout.getTabAt(2).setCustomView(layout3);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPager pager = (ViewPager) view.findViewById(R.id.compager);
CommunityPagerFragment adapter = new CommunityPagerFragment(getChildFragmentManager());
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
//tabLayout.set
return view;
I'm kind of lost, I don't know why my Tabs remain invisible. Thanks in advance.
EDIT Here is my adapter:
public class CommunityPagerFragment extends FragmentPagerAdapter {
public CommunityPagerFragment(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new BlogFragment();
case 1:
return new NewsFragment();
case 2:
return new FAQFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
public class BlogFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
return view;
}
}
public class NewsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
/*ProgressBar loadingAnim = new ProgressBar(getContext());
loadingAnim.setLayoutParams(new LinearLayout.LayoutParams(40,40));
container.addView(loadingAnim);*/
return view;
}
}
public class FAQFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.communitylistview, container, false);
return view;
}
}
}
You aready have a viewpager, why don't you use setupWithViewPager method?
getTabbar().setupWithViewPager(viewPager);
Add fragment to adapter
BaseFragmentPagerAdapter adapter = new BaseFragmentPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ExampleListedRecyclerViewFragment(), "Tab title 1", false);
adapter.addFragment(new ExampleGridedRecyclerViewFragment(), "Tab title 2", false);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
ViewPager adapter
public class BaseFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public BaseFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
addFragment(fragment, title, true);
}
public void addFragment(Fragment fragment, String title, boolean hasOptionsMenu) {
fragment.setHasOptionsMenu(hasOptionsMenu);
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
if you want to set an icon to tab item instead of text title:
tabLayout.getTabAt(i).setIcon(iconDrawable);
more detials please see my project
https://github.com/DanielShum/MaterialAppBase/blob/master/materialAppBaseLibrary/src/main/java/com/daililol/material/appbase/base/BaseTabbableActionbarActivity.java
https://github.com/DanielShum/MaterialAppBase/
Try this:
Element tab XML where you want:
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_scrollFlags="scroll|enterAlways"
></android.support.design.widget.TabLayout>
In your MainActivity:
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setTabMode(TabLayout.MODE_FIXED);
tabs.addTab(tabs.newTab().setText("Tab 1"));
tabs.addTab(tabs.newTab().setText("Tab 2"));
tabs.addTab(tabs.newTab().setText("Tab 3"));
The key was to setupWithViewpager first before managing the tabs.
setupWithViewpager first before managing the tabs.
xml layout:
<android.support.v7.widget.Toolbar`enter code here`
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/coloricon" />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabMode="fixed" >
<android.support.design.widget.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.design.widget.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#android:color/white"/>
in Fragment :
public class myfragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_xml, container, false);
TabLayout tabLayout = V.findViewById(R.id.tablayout);
TabItem tabScan = V.findViewById(R.id.tab1);
TabItem tabCreate = V.findViewById(R.id.tab2);
final ViewPager viewPager = (ViewPager) V.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//setupWithViewpager first before managing the tabs.
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.getTabAt(0).setText("1");
tabLayout.getTabAt(1).setText("2");
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) {
}
});
return V;
}
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new fragment1();
case 1:
return new fragment2();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
I am creating a fragment in which I'm using a clickable linearLayout as a button
I have created all the necessary methods and implemented the OnClickListener interface to the class but when i click the layout nothing happens
Here is my LinearLayout and TextView from xml and java code.
<LinearLayout
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="50dip"
android:layout_weight="1"
android:clickable="true"
android:background="#drawable/button_layout"
android:layout_margin="1dip">
<LinearLayout
android:orientation="vertical"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="e"
android:textColor="#color/abc_primary_text_disable_only_material_dark"
android:gravity="top"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="π"
android:gravity="bottom"/>
</LinearLayout>
</LinearLayout>
The mainview TextView is
<TextView android:id="#+id/mainview"
android:layout_width="match_parent"
android:background="#color/button_material_light"
android:layout_height="60dip"
android:layout_weight="1"/>
Class code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}
I also tried debugging the program and find out that the method is not called on clicking the Layout.
Thanks to rahul to remind me to pass the "this" Object in the setOnClickListener of the Clickable LinearLayout Which I'm using as the Button
So first I assign the id to the layout by android:id="#+id/pie"
then setting the listner in the code then the new code is
public class HomeFragment extends Fragment implements View.OnClickListener{
TextView mainView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainView = (TextView) getActivity().findViewById(R.id.mainview);
//This is the New Part
((LinearLayout)getActivity().findViewById(R.id.pie))
.setOnClickListener(this);
}
public static HomeFragment newInstance(int i){
HomeFragment homeFragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt("index", i);
homeFragment.setArguments(args);
return homeFragment;
}
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity)activity).
onSectionAttached(getArguments().getInt("index"));
}
#Override
public void onClick(View view) {
mainView.setText("ghalib");
}
}