I have implemented my map fragment with map as <fragment> in two places:
(main) <DrawerLayout> --> <FrameLayout> (container)
--> (fragment inflated) <CoordinatorLayout> --> <LinearLayout> --> <ViewPager2> (container)
--> (fragment inflated) <NestedScrollView> --> <LinearLayout> --> <ViewPager2> (container)
--> (map fragment inflated) <FrameLayout> --> <fragment>
(main) <LinearLayout> --> <LinearLayout> (container)
--> (fragment inflated) <LinearLayout> --> <ViewPager2> (container)
--> (map fragment inflated) <FrameLayout> --> <fragment>
The problem is that in the first case my map flickers when I click on a map marker or when I click on an ImageView from my map fragment ViewGroup that does nothing but toggle icons visibility between GONE and VISIBLE. The second case works fine. It gives me a hint that map's blinking is due to other views changing their visibility in the NestedScrollView. Maybe it is also because of overwhelming number of parents.
I tried to implement android:layerType="hardware" but it doesnt help. Also, when the visibility is toggled between VISIBLE and INVISIBLE all works fine, but this is not the solution.
I have recorded the told map's behaviour and attached it here. On the record I click on a ToggleButton and toggle a small tick icon between GONE and VISIBLE.
Any ideas how to fix that?
Code
Main Activity
It is a Navigation Drawer Activity
public class MainActivityC extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_c);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_c, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Fragment 1
This fragment holds ViewPager2
public class GalleryFragment extends Fragment{
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
private Context context;
private ViewPager2 viewPager2;
private TabLayout tabLayout;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
context = getActivity();
initTab();
}
private void initTab() {
viewPager2 = getView().findViewById(R.id.viewpager2_walks_saved);
viewPager2.setAdapter(new WalksSavedPagerAdapter(getActivity()));
viewPager2.setUserInputEnabled(false); // NO SCROLL
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
switch (position) {
case 0:
String text1 = "Walks History";
((MainActivityC) context).getSupportActionBar().setTitle(text1);
break;
case 1:
String text2 = "Walks Statistics";
((MainActivityC) context).getSupportActionBar().setTitle(text2);
break;
}
}
});
tabLayout = getView().findViewById(R.id.tabLayout_walks_statistics);
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position) {
case 0:
tab.setText("Walks History");
break;
case 1:
tab.setText("Walks Statistics");
break;
}
}
}
);
tabLayoutMediator.attach();
}
}
Layout:
<androidx.coordinatorlayout.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:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="?attr/colorPrimary">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|snap"
android:elevation="4dp">
<TextView
android:id="#+id/drawer_fragment_saved_walks_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Saved Walks"
android:textSize="30sp"
android:textColor="#color/white"
android:layout_gravity="center"/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="0dp"
android:layout_width="match_parent"
app:layout_collapseMode="pin" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
<!--android:layout_height="?attr/actionBarSize"-->
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<!-- Tab to chose between Saved Walks and Statistics -->
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout_walks_statistics"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:layout_gravity="bottom"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:tabPaddingBottom="4dp"
app:tabPaddingTop="4dp" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager2_walks_saved"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Fragment 2
This fragment is shown in the ViewPager2 and has its own ViewPager2
public class StatisticsFragment extends Fragment {
private ViewPager2 viewPager2;
private TabLayout tabLayoutViewPager;
private StatisticsPagerAdapter statisticsPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_walks_statistics, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init(){
statisticsPagerAdapter = new StatisticsPagerAdapter(getActivity());
viewPager2 = getView().findViewById(R.id.viewpager2_statistics);
viewPager2.setAdapter(statisticsPagerAdapter);
viewPager2.setUserInputEnabled(false); // NO SCROLL
tabLayoutViewPager = getView().findViewById(R.id.tabLayout_statistics);
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
tabLayoutViewPager, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position) {
case 0:
tab.setText("Events");
break;
case 1:
tab.setText("Chronology");
break;
case 2:
tab.setText("Heat Map");
break;
}
}
}
);
tabLayoutMediator.attach();
}
}
Layout:
<androidx.core.widget.NestedScrollView
android:id="#+id/heatmap_nested_scroll_view"
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"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout_statistics"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#android:color/transparent"
android:layout_marginTop="8dp"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:tabPaddingBottom="4dp"
app:tabPaddingTop="4dp" />
<View
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#android:color/darker_gray" />
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager2_statistics"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
Fragment 3 with GoogleMap
This fragment is shown in the ViewPager2 and holds the fickering map
public class StatisticsHeatmapFragment extends Fragment implements OnMapReadyCallback,
CompoundButton.OnCheckedChangeListener {
private Context context;
private Fragment parentFragment;
private ToggleButton iconRescale;
private ImageView iconCheck;
private MapFragment mapFragment;
private GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_statistics_heatmap, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initiate();
}
#SuppressLint("ClickableViewAccessibility") // Due to the touch listener
private void initiate() {
context = getActivity();
// A neat way to find the parent fragment in a child ViewPager fragment
List<Fragment> fragment = getActivity().getSupportFragmentManager().getFragments();
for (Fragment f:fragment) {
if (f instanceof StatisticsFragment){
parentFragment = f;
}
}
ImageView transparentImageView = (ImageView) getView().findViewById(R.id.heatmap_transparent_image);
// Tag is automatically given by ViewPager2 like "f" + position, but I have overwritten it.
// So the StatisticsFragment is "f101". There the NestedScrollView locates.
final NestedScrollView nestedScrollView = (NestedScrollView)
getActivity().getSupportFragmentManager().findFragmentByTag("f101").getView();
// The warning comes up because Android wants to remind you to think about the blind or visually impaired people who may be using your app
transparentImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
nestedScrollView.requestDisallowInterceptTouchEvent(true);
// Disable touch on transparent view
return false;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
nestedScrollView.requestDisallowInterceptTouchEvent(false);
return true;
case MotionEvent.ACTION_MOVE:
nestedScrollView.requestDisallowInterceptTouchEvent(true);
return false;
default:
return true;
}
}
});
mapFragment = (MapFragment) getActivity().getFragmentManager()
.findFragmentById(R.id.map_statistics);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
initToggleButtons();
}
private void initToggleButtons() {
iconCheck = getView().findViewById(R.id.icon_check_heatmap_stats);
iconRescale = getView().findViewById(R.id.icon_rezoom_heatmap_stats);
iconRescale.setChecked(true);
iconRescale.setOnCheckedChangeListener(this);
}
/**
* CheckChange listener for events icon (ToggleButton)
*/
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.equals(iconRescale)){
if (isChecked) {
DrawableCompat.setTint(
DrawableCompat.wrap(iconRescale.getBackground()),
ContextCompat.getColor(context, R.color.black));
iconCheck.setVisibility(View.VISIBLE);
Toast.makeText(context, "Map scale to the data is ON", Toast.LENGTH_SHORT).show();
} else {
DrawableCompat.setTint(
DrawableCompat.wrap(iconRescale.getBackground()),
ContextCompat.getColor(context, R.color.common_google_signin_btn_text_light));
iconCheck.setVisibility(View.GONE);
Toast.makeText(context, "Map scale to the data is OFF", Toast.LENGTH_SHORT).show();
}
}
}
}
Layout:
<FrameLayout 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">
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.MapFragment"
android:id="#+id/map_statistics"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:mapType="normal" />
<ImageView
android:id="#+id/heatmap_transparent_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#android:color/transparent" />
<ImageView
android:id="#+id/icon_check_heatmap_stats"
android:layout_width="14dp"
android:layout_height="14dp"
android:background="#drawable/ic_baseline_check_24"
android:backgroundTint="#android:color/holo_red_light"
android:layout_gravity="end|top"
android:layout_marginTop="28dp"
android:layout_marginEnd="69dp"/>
<ToggleButton
android:id="#+id/icon_rezoom_heatmap_stats"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/ic_baseline_zoom_out_map_24"
android:backgroundTint="#color/black"
android:layout_gravity="end|top"
android:layout_marginTop="20dp"
android:layout_marginEnd="60dp"
android:textOn=" "
android:textOff=" "/>
</FrameLayout>
P.S. Multiple clicks on the icon are required to spot the problem using this code.
I have solved my own problem, however other solutions are more than welcome.
The issue is that the map's parent <NestedScrollView> has android:fillViewport="true" attribute, which forces the view to stretch its content to fill the viewport.
The solution is to set the map's view to a constant height. So, android:layout_height="match_parent" should be changed to android:layout_height="500dp" for example. Also, the height could be set dinamically as appropriate.
Addition
Google Map view in NestedScrollView can be kept android:layout_height="match_parent". Then, to fix the view's height (which is needed to avoid the flickers) add this snippet in onCreate or onCreateView in Activity or Fragment respectively:
view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right,
int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
int height = v.getHeight();
ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = height;
view.setLayoutParams(params);
view.removeOnLayoutChangeListener(this);
}
});
Related
I have created A layout and I dynamically add tabs according to data I receive. I do the same with fragments updating the Text View dynamically. Although when the layout loads and if I swipe through the fragments or view pager (sorry I am new to all these hope my terminology is right) they update just okay (meaning there is sometimes lag in updating not much of an issue) and with right data. although, if in fresh I open the layout and click on tab to change my fragments I get no data or wrong data. Example:- when Layout loads for first time my first & third tab load up fine. If I click on a second Tab (not swiping but touching the tabs on top for the whole time), my second tab doesn't have any data in its fragment. On moving round here and there selecting tabs randomly first tab loads second tabs data, but second tab never loads anything. Its not the same when I swipe if I load page new or for first time.
Let me know where I am doing wrong. Thank you.
Here is my code:-
Layout file - show_score.xml
<android.support.design.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.lp.activity.ShowScorePassagesActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/children_school"
android:scaleType="centerCrop"
android:alpha="0.5"
android:layout_below="#+id/appBackBar"/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<include android:id="#+id/appBackBar"
layout="#layout/detail_appbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/passagetabs"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Fragment File - fragment_show_score_passage.xml
<android.support.constraint.ConstraintLayout 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:id="#+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lp.activity.ShowScorePassagesActivity$PlaceholderFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<android.support.v7.widget.CardView
android:id="#+id/cardView4"
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardElevation="5dp"
android:scaleType="fitXY"
android:layout_margin="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<TextView
android:id="#+id/showScore"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="18dp"
android:scaleType="fitXY"
android:text="TextView"
android:autoLink="web"
android:linksClickable="true"
android:padding="20dp"
android:clipToPadding="false"/>
</ScrollView>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardElevation="5dp"
android:layout_below="#+id/cardView4"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/scrollbar_shape_style">
<GridView
android:id="#+id/fluencyAudioGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="2dp"
android:verticalSpacing="5dp"
android:columnWidth="120dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clipToPadding="false"
android:stretchMode="spacingWidthUniform"
layout="#layout/icons_for_dashboard"
android:scrollbarThumbVertical="#drawable/scroolbar_style"
android:scrollbarTrackVertical="#drawable/scroolbar_style_background">
</GridView>
</ScrollView>
</android.support.v7.widget.CardView>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
And the main Java File where the magic happens - ShowScorePassageActivity.java
public class ShowScorePassagesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public GridView gridView;
public ArrayList<String> gridItems = new ArrayList<String>();
public static TextView fragTextView;
static String fragNewTextView = "";
public static ArrayList<String> fluencyMarksList = new ArrayList<>();
public TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_score_passages);
Intent in = getIntent();
String intentData = in.getStringExtra("intentData");
String fluencyMarks = in.getStringExtra("fluencyMarks");
tabLayout = (TabLayout) findViewById(R.id.passagetabs);
String mFluencyMarkList []= fluencyMarks.split("#");
fluencyMarksList = new ArrayList<String>(Arrays.asList(mFluencyMarkList));
int count = 1;
int counts=fluencyMarksList.size();
for(int i = 0; i < counts; i++){
tabLayout.addTab(tabLayout.newTab().setText("Passage "+count));
count=count+1;
}
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();
}
});
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
int position = tab.getPosition();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0), Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1) , Html.FROM_HTML_MODE_COMPACT));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2) , Html.FROM_HTML_MODE_COMPACT));
}
} else {
if (position ==0){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
else if (position ==1){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(1)));
}
else if (position ==2){
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(2)));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
fragTextView.setText("");
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#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_show_score_passages, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_show_score_passages, container, false);
fragTextView = (TextView) rootView.findViewById(R.id.showScore);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0) , Html.FROM_HTML_MODE_COMPACT));
} else {
fragTextView.setText(Html.fromHtml(fluencyMarksList.get(0)));
}
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
Fragment fragment = null;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs=NumOfTabs;
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
This is what I did:
It is only a example of what worked for me in the hopes of helping you
In OnCreate:
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
this.addPages(mViewPager);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.mTab_ID);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(listener(mViewPager));
Then add the fragments to the TabLayout by doing:
//ADD ALL PAGES TO TABLAYOUT
private void addPages(ViewPager pager) {
adapter = new MyFragPagerAdapter(getSupportFragmentManager());
adapter.addPage(new FragmentAdapter1());
adapter.addPage(new FragmentAdapter2());
adapter.addPage(new FragmentAdapter3());
//SET ADAPTER TO PAGER
pager.setAdapter(adapter);
}
Then implement TabLayout click events OnTabSelectedListener by doing:
//TabLayout Click Events
private TabLayout.OnTabSelectedListener listener(final ViewPager pager) {
return new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
}
I have a AppBarLayout with TabLayout in a fragment that is into an Activity that has a Toolbar. But between toolbar and TabLayout appears a space, i don't know where it comes from.
fragment_packs.xml
<FrameLayout 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="studio.com.archeagemanager.EventosFragment">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="studio.com.archeagemanager.PacksFragment">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
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="match_parent"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabTextColor="#ffffff" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
PacksFragment.java
public class PacksFragment extends Fragment {
public PacksFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_packs, container, false);
AppBarLayout appBarLayout = (AppBarLayout) view.findViewById(R.id.appbar);
appBarLayout.setExpanded(false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
viewPager.setAdapter(new PagerAdapter(getFragmentManager()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
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 view;
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private String[] tabTitles = new String[]{"Tab1", "Tab2", "Tab3", "Tab4"};
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TabFragmentA();
case 1:
return new TabFragmentA();
case 2:
return new TabFragmentA();
case 3:
return new TabFragmentA();
default:
return null;
}
}
#Override
public int getCount() {
return tabTitles.length;
}
}
}
In your CoordinatorLayout
instead of
android:fitsSystemWindows="true"
apply
android:fitsSystemWindows="false"
Here is a good Documentation why and when you should use a android:fitsSystemWindows
System windows are the parts of the screen where the system is drawing either non-interactive (in the case of the status bar) or interactive (in the case of the navigation bar) content.
Most of the time, your app won’t need to draw under the status bar or the navigation bar, but if you do: you need to make sure interactive elements (like buttons) aren’t hidden underneath them. That’s what the default behavior of the android:fitsSystemWindows=“true” attribute gives you: it sets the padding of the View to ensure the contents don’t overlay the system windows.
A few things to keep in mind:
1)fitsSystemWindows is applied depth first — ordering matters: it’s the first View that consumes the insets that makes a difference
2) Insets are always relative to the full window — insets may be applied even before layout happens, so don’t assume the default behavior knows anything about the position of a View when applying its padding
3) Any other padding you’ve set is overwritten — you’ll note that paddingLeft/paddingTop/ etc is ineffective if you are using android:fitsSystemWindows=”true” on the same View
When You are using Navigation Drawer, there is app_bar_main.xml where AppBarLayout is already present, so removing both AppBarLayout and Toolbar from app_bar_main.xml will solve the problem.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
in both app_bar_main.xml and content_main.xml AppBarLayout and Toolbar present.
removing from one will solve the problem
How can I change the text size of TextView of a fragment. I need it, because text size is small, maybe some users want it to get bigger.
I see, some people advise to use seekbar, or pinch-to-zoom but I can not make it work in a fragment.
Thanks for your help.
my fragment_one.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"
tools:context="org.aultoon.webovietab.fragments.OneFragment"
android:id="#+id/oneFragmentId"
>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="top|center"
android:gravity="center"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tvFragmentOne"
android:text="#string/turkce1"
android:textSize="27sp"
android:textIsSelectable="true"
android:layout_margin="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
</ScrollView>
here is the my OneFragment.java
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
here is the my activity
public class SimpleTabsActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "tab1");
adapter.addFragment(new TwoFragment(), "tab2");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.aboutMenuItem:
Intent i = new Intent(this, About_Activity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
First, please read the following Q&A about the textsize "sp" unit in android. You should understand why it used sp as unit for textView and your question should be solved.
Should use "sp" instead of "dp" for text sizes
What is the difference between "px", "dp", "dip" and "sp" on Android?
Android sp vs dp texts - what would adjust the 'scale' and what is the philosophy of support
http://www.singhajit.com/tutorial-1-android-ui-desgin-and-styling/
Now, you should know the usage of "sp" unit in TextView since it can be adjusted due to the user accessibility setting. That's mean if your boss cannot see it clearly, he/she can set the font size setting in the devices instead of code change.
If you still need workaround for the programming. Here is the solution
I have added the seekbar in your fragment layout.
Update xml.
<RelativeLayout android:id="#+id/oneFragmentId"
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"
>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"/>
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar"
android:fadingEdge="none"
android:fillViewport="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top|center"
android:gravity="center"
android:orientation="vertical"
>
<TextView
android:id="#+id/tvFragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:text="Hello world"
android:textIsSelectable="true"
android:textSize="27sp"
/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I have change your textView text as "Hello world" for testing, please change back to your own string resource.
Here is the fragment code.
public class OneFragment extends Fragment {
//static WebView mWebview;
public OneFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
final TextView tvFragmentOne = (TextView) rootView.findViewById(R.id.tvFragmentOne);
SeekBar lSeekBar = (SeekBar) rootView.findViewById(R.id.seekBar);
lSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
tvFragmentOne.setTextSize(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
return rootView;
}
}
If you like to use other control pinch to zoom, up/down button or other control component to change the text size of the textview, you can do it with the following procedures:
Change other widget instead of seekbar
Change the listener for listening the component control change( like OnSeekBarChangeListener )
Reset the textView size
I want to be able to click on buttons to navigate forward and backward through several views as well as swiping left or right between views.
So I decided to implement the ViewPager for swiping between multiple views.
Here's my code:
layout xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
</RelativeLayout>
Here's my activity:
public class CollectionPager extends Activity {
private PagerAdapter pagerAdapter;
ActionBar actionbar;
MyAdapter myAdapter;
private Context context;
private TextView textView;
private int currentPage;
ViewPager viewPager;
int progressChanged = 0;
public static final String TAG = "CollectionPager";
public CollectionPager() {
context = this;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Initialize the back button and add an onClick event listener to the button
final ImageView back_button = (ImageView) findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
//Initialize the forward button and add an onClick event listener to the button
final ImageView forward_button = (ImageView) findViewById(R.id.forward_nav_arrow);
forward_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the last item
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
});
final Button save_button = (Button) findViewById(R.id.save);
save_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//save
}
});
final Button ignore_button = (Button) findViewById(R.id.ignore);
ignore_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//ignore
}
});
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
private class MyAdapter extends PagerAdapter {
int NumberOfPages = 10;
LayoutInflater inflater = (LayoutInflater) CollectionPager.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public int getCount() {
return NumberOfPages;
}
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
parent.addView(view,0);
return view;
}
#Override
public void destroyItem(ViewGroup parent, int position, Object object) {
((ViewPager) parent).removeView((View) object);
}
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
#Override
public Parcelable saveState() {
return null;
}
}
}
The onClickEvent is detected but here's a screenshot on what is happening to the view. Two view on top of each other. One view is fixed on the screen and the other one is scrolling correctly.
I'm not sure why this happens. What is causing this to occur in my code?
EDIT: Here's a video highlighting the issue: https://www.dropbox.com/s/6x5qa16xyttzrwa/VIDEO0041.mp4?dl=0
Change
#Override
public boolean isViewFromObject(View parent, Object object) {
return parent== ((View) object);
}
to
#Override
public boolean isViewFromObject(View v, Object o) {
return parent == object;
}
Update:
After watching your movie your problem is you put some static wedget on the top of your viewpager, so remove that, which means your layout will become something like this:
This is your main_activity.xml you must assign it to your activity by function setContentView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
</RelativeLayout>
then at instantiateItem use below layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
>
<ImageView
android:id="#+id/apple"
android:layout_width="200sp"
android:layout_height="150sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/apple"
android:contentDescription="apple"/>
<TextView
android:id="#+id/number"
android:layout_width="100sp"
android:layout_height="55sp"
android:layout_marginTop="47dp"
android:layout_below="#+id/apple" android:layout_alignStart="#+id/apple"/>
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save"
android:layout_alignTop="#+id/ignore" android:layout_toStartOf="#+id/apple"/>
<Button
android:id="#+id/ignore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Ignore"
android:layout_alignParentBottom="true" android:layout_toEndOf="#+id/apple"/>
<ImageView
android:id="#+id/back_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_back"
android:contentDescription="back">
</ImageView>
<ImageView
android:id="#+id/forward_nav_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_forward"
android:layout_alignParentTop="true" android:layout_alignParentEnd="true"
android:contentDescription="forward">
</ImageView>
your main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.collection);
viewPager = (ViewPager) findViewById(R.id.viewPager);
myAdapter = new MyAdapter();
viewPager.setAdapter(myAdapter);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
//Attach the page change listener inside the activity
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
//This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
//get position
currentPage = position;
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int i) {
//get state
}
});
}
then assign your click listener of your main activity at this function
#Override
public Object instantiateItem(ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.collection, parent, false);
ImageView imageView = (ImageView) view
.findViewById(R.id.apple);
imageView.setImageResource(R.drawable.apple);
final ImageView back_button = (ImageView) view.findViewById(R.id.back_nav_arrow);
back_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//it doesn't matter if you're already in the first item
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
});
parent.addView(view,0);
return view;
}
On the image, a drawer layout is inside a ViewPager + Tab. I want to open the Drawer Menu but the when I click the Home button, does nothing. I just wanted to display the menu on this scenario.
On some point, when I swipe to the right the drawer to be opened, but instead the viewPager got triggered and transferred to the next page.
Could I possibly put a border like drawable instead, in the drawer menu so that by the time I click the border or drag it it will open the drawer? The blue line is just an added edit but not in the actual scenario.
switch(arg0){
/** Android tab is selected */
case 0:
DrawerLayoutFragment androidFragment = new DrawerLayoutFragment();
data.putInt("current_page", arg0+1);
androidFragment.setArguments(data);
return androidFragment;
DrawerLayoutFragment
public class DrawerLayoutFragment extends Fragment implements SimpleGestureListener{
private SimpleGestureFilter detector;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
detector = new SimpleGestureFilter(getActivity(),this);
mTitle = mDrawerTitle = getActivity().getTitle();
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.drawer_layout_fragment, container, false);
mPlanetTitles = rootView.getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) rootView.findViewById(R.id.drawer_layout);
mDrawerList = (ListView) rootView.findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(getActivity(),
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
//enable ActionBar app icon to behave as action to toggle nav drawer
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
getActivity().getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActivity().getActionBar().setTitle(mTitle);
getActivity().invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
Log.d("onDrawerClosed", "inside");
}
public void onDrawerOpened(View drawerView) {
getActivity().getActionBar().setTitle(mDrawerTitle);
getActivity().invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
return rootView;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return getActivity().onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/u p action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
default:
Log.d("onOptionsItemSelected", "inside");
return super.onOptionsItemSelected(item);
}
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
Log.d("DrawerItemClickListener", "inside");
}
}
private void selectItem(int position) {
Log.d("selectItem", "inside");
// update the main content by replacing fragments
PlanetFragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentTransaction ft = getChildFragmentManager().beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void setTitle(CharSequence title) {
mTitle = title;
getActivity().getActionBar().setTitle(mTitle);
}
public static class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
//Simple Gesture
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return getActivity().dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
mDrawerLayout.openDrawer(mDrawerList);
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
mDrawerLayout.closeDrawer(mDrawerList);
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
Toast.makeText(getActivity(), "Double Tap", Toast.LENGTH_SHORT).show();
}
}
drawer_layout_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
Sorry sir, iDroid for not updating this quick.
Update:
I also faced the same problem and then i tired SlidingLayer.
You can give it a try as well, that's exactly what you need.
Enjoy Coding...
=====================================================
It seems like you want to add another view in the DrawerLayout. If it is then you can do it like below:
Here is my code of xml layout having drawerlayout:
<?xml version="1.0" encoding="UTF-8"?>
<!--
A DrawerLayout is intended to
be used as the top-level content view using match_parent for both width and
height to consume the full space available.
-->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="UnusedResources"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--
As the main content view, the view below consumes the entire space available
using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat this as
a sliding drawer on the left side for left-to-right languages and on the
right side for right-to-left languages. The drawer is given a fixed width
in dp and extends the full height of the container. A solid background is
used for contrast with the content view.
-->
<LinearLayout android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="horizontal">
<LinearLayout
android:layout_width="240dp"
android:layout_height="match_parent"
android:background="#drawable/list_background_gradient"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="10dp"
android:gravity="center_vertical"
android:background="#drawable/search_box"
android:orientation="horizontal">
<EditText
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:paddingLeft="13dp"
android:paddingRight="13dp"
android:layout_weight="1"
android:singleLine="true"
android:hint="SEARCH USER"
android:maxLength="30"
android:textColor="#FFFFFF"
android:background="#android:color/transparent"
android:textSize="15sp" />
<ImageView android:layout_height="20dp"
android:layout_width="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_gravity="center"
android:src="#drawable/category_search"
/>
</LinearLayout>
<TextView android:layout_width="240dp"
android:layout_height="wrap_content"
android:text="SELECT A LINE"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_marginBottom="2dp"
android:background="#43BBED"
/>
<ListView
android:id="#+id/list_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_margin="2dp"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:scrollbars="none" />
</LinearLayout>
<ImageView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/ic_launcher"
android:scrollX="20dp"
/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
And it looks something like this: