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
Related
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);
}
});
I am trying to add gridview for my layout.
The MainActivity contains 5 number of tabs , where first tab is AlbumsActivity.
AlbumsActivity
public class AlbumsActivity extends Fragment{
public AlbumsActivity() {
// 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.activity_albums, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
GridView gridView = (GridView) findViewById(R.id.grid_view);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
}
}
ImageAdapter.java
I am using this class adapter to populate the grids in AlbumsActivity.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.splas,
R.drawable.abc,
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
return imageView;
}
}
grid_layout.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
activity_albums.xml
This is layout file for AlbumsActivity , where i want to show grids in page.
<LinearLayout 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:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
</LinearLayout>
I think you are doing it wrong.
MainActivity - 5 Tabs and one framelayout
AlbumsActivity (Fragment) - Activity_Albums.xml (TextView, GridView)
ImageAdapter (BaseAdapter) - Custom Layout (ImageView)
3 -> 2 (Gridview) -> 1
if not you have to create, set parameters and inject gridview with custom layout to main layout programatically
//Try this
activity_albums.xml
<LinearLayout 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:padding="16dp"
android:orientation="vertical"
tools:context="com.example.android.musiclist.AlbumsActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/ald"
android:textSize="20sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
AlbumsActivity
public class AlbumsActivity extends Fragment{
private View view;
private FrameLayout fl;
private GridView gv;
public AlbumsActivity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_albums,container,false);
fl = view.findViewById(R.id.frameLayout);
gv = findViewById(R.id.grid_view);
gv.setAdapter(new ImageAdapter(this));
fl.addView(gv);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Or Something similar, I am too lazy to type everything now. just google search "android custom arrayadapter" and you will find tons of examples. It's really simple
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) {
}
};
}
There is an activity with container for fragments, which with a start of activity added ViewPagerFragment. There is a RecyclerView inside of MainFragment (which is tab) which is displayed but not filled with a data.
Tried to change width and high from 0 to Match_Parent and Fixed_Size. Also changed ConstraintLayout to RelativeLayout.Using theme android:theme="#style/MyMaterialTheme"
style.xml
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">
</style>
E/RecyclerView: No adapter attached; skipping
MainActivity.class
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private AdView mAdView;
private FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
mAdView.loadAd(adRequest);
mFragmentTransaction = getSupportFragmentManager()
.beginTransaction()
.add(R.id.container_frame, new ViewPagerFragment());
mFragmentTransaction.commit();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
}
#Override
protected void onPause() {
super.onPause();
mAdView.pause();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimaryDark"
tools:context="com.newakkoff.justad.Activities.MainActivity">
<RelativeLayout
ads:layout_constraintBottom_toTopOf="#+id/adView"
ads:layout_constraintTop_toTopOf="parent"
ads:layout_constraintLeft_toLeftOf="parent"
ads:layout_constraintRight_toRightOf="parent"
android:id="#+id/container_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="0dp"
ads:adSize="BANNER"
ads:adUnitId="#string/banner_ad_unit_id"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1"
android:layout_height="50dp">
</com.google.android.gms.ads.AdView>
</android.support.constraint.ConstraintLayout>
ViewPagerFragment.class
public class ViewPagerFragment extends Fragment {
private ViewPager mViewPager;
private Toolbar mToolbar;
private TabLayout mTableLayout;
int i = 1;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_view_pager, container, false) ;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager_main);
mViewPager.setAdapter(new CustomPagerAdapter(getActivity()));
mViewPager.setCurrentItem(1);
mTableLayout = (TabLayout) view.findViewById(R.id.tabs);
mTableLayout.setupWithViewPager(mViewPager);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
}
fragment_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="#+id/appBarLayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager_main"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="0dp"
android:layout_height="0dp">
MainFragment.class
public class MainFragment extends Fragment {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayoutManager = new LinearLayoutManager(this.getActivity(),LinearLayoutManager.VERTICAL,false);
mAdapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five", "test six", "test seven"});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
tools:listitem="#layout/card_item"
android:background="#color/colorPrimary"/>
</android.support.constraint.ConstraintLayout>
CustomPageAdapter.class
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ModelPager modelsPager = ModelPager.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelsPager.getLayoutResId(), container, false);
container.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return ModelPager.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelPager customPagerEnum = ModelPager.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
ModelPager.class
public enum ModelPager {
SEND_FRAGMENT(R.string.send_fragment_tab,R.layout.fragment_send),
MAIN_FRAGMENT(R.string.main_fragment_tab, R.layout.fragment_main),
ABOUT_FRAGMENT(R.string.about_fragment_tab, R.layout.fragment_about);
private int mTitleResId;
private int mLayoutResId;
ModelPager(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
MyAdapter.class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
static class MyViewHolder extends RecyclerView.ViewHolder {
private static final String TAG = "My Recycler Adapter";
CardView mCardView;
TextView mTextView;
MyViewHolder(View v) {
super(v);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
}
});
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter( String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
card_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="68dp" >
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="62dp"
card_view:cardCornerRadius="4dp"
card_view:elevation="14dp">
<TextView
android:id="#+id/tv_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:gravity="center" >
</TextView>
</android.support.v7.widget.CardView>
</RelativeLayout>
The only place that can logically have anything to do with that error is mRecyclerView.setAdapter(mAdapter); since its the only RecyclerView.
Looking at the documentation mAdapter is allowed to be null to represent no adapter. So either that variable is null or it is does not properly implement the RecyclerView.Adapter interface.
So this has been bugging me for like a week and I haven't found the answer yet.
Basically I have this MainActivity which contains the main code and a fragment that work for the listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button bNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 RoomServer(), "Room Server");
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);
}
}
}
RoomServer.java
public class RoomServer extends ListFragment implements OnItemClickListener{
public RoomServer() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rs, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(getListView().CHOICE_MODE_MULTIPLE);
getListView().setTextFilterEnabled(true);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.rs_list, android.R.layout.simple_list_item_checked);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Fragment_rs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.RoomServer">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/bNext_rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginBottom="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
activity_main.xml
<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:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The items of listview r declared inside strings.XML
As u can see I'm using CHOICE_MODE_MULTIPLE to create checkbox in the listview. And now I'm stuck at how to get the value of this checkbox. I'm planning to use Volley to send value to my database by a button click. Most of the answer I saw was using the isChecked and stuff but I dont really understand how to implement it in my array adapter.
You can either implement a custom array adapter yourself, or use this method in the ListView class to get a SparseBooleanArray of the indexes of the selected items:
//Submit button example
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get base list
String[] items = getActivity().getResources().getStringArray(R.array.rs_list);
//Get selected items & set intent args
SparseBooleanArray selectedItems = getListView().getCheckedItemPositions();
ArrayList<String> argList = new ArrayList<>();
for (int i = 0; i < selectedItems.size(); i++) {
argList.add(items[selectedItems.keyAt(i)]);
}
//Start activity
Intent intent = new Intent();
intent.putStringArrayListExtra("SelectedItems", argList);
getActivity().startActivity(intent);
}
});