RecyclerView No adapter attached - java

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.

Related

How do I inflate a RecylerView? Why do I get an RecyclerView has no LayoutManager error?

In my task I have to make for the Recycle View it's own xml file. But now I get the error of "RecyclerView has no LayoutManager" at the point I inflate it.
Even so my task states that I have to include the Fragment part and service like this:
Create a single instance of the MusicStoreService in the MainActivity and provide a getter method.
In the ProductListFragment use (MainActivity) getActivity() to access the parent activity and from there the service.
Pass the service on to the ProductListAdapter's constructor
Here are the files:
Main.java
public class MainActivity extends AppCompatActivity {
MusicStoreService music;
public MainActivity() {
super(R.layout.main);
System.out.println("MS2021: MainActivity/"+"MainActivity".hashCode()+": MainActivity() - created");
}
#Nullable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
music = new MusicStoreServiceMock();
setContentView(R.layout.product_list_fragment);
if (savedInstanceState == null) {
System.out.println("MS2021: MainActivity/" + "MainActivity".hashCode() + " onCreate()");
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.productlist_recycler, ProductListFragment.class, null)
.commit();
System.out.println();
}
}
public MusicStoreService getMusic() {
return music;
}
ProductListFragement.java
public class ProductListFragment extends Fragment {
RecyclerView recyclerView;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_list_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
try {
recyclerView.setAdapter(new ProductListAdapter(((MainActivity) getActivity()).getMusic()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ProductListAdapter pld = null;
try {
pld = new ProductListAdapter(new MusicStoreServiceMock());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
recyclerView.setAdapter(pld);
}
}
ProductListAdapter.java
public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.ViewHolder>{
private List<Product> products;
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView produzer;
private TextView productName;
private TextView priceNumber;
public ViewHolder(View view,TextView produzer, TextView productName, TextView price) {
super(view);
this.produzer = produzer;
this.productName = productName;
this.priceNumber = price;
}
public TextView getProduzer() {
return produzer;
}
public TextView getProductName() {
return productName;
}
public TextView getPriceNumber() {
return priceNumber;
}
public void setProduzer(TextView produzer) {
this.produzer = produzer;
}
public void setProductName(TextView productName) {
this.productName = productName;
}
public void setPriceNumber(TextView priceNumber) {
this.priceNumber = priceNumber;
}
}
public ProductListAdapter(MusicStoreService dataSet) throws FileNotFoundException {
products = dataSet.getProducts();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout
.product_list_layout, viewGroup, false);
return new ViewHolder(view,view.findViewById(R.id.produzer),view.findViewById(R.id.productName),view.findViewById(R.id.priceNumber));
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setCurrency(Currency.getInstance("EUR"));
String price = format.format(products.get(position).getPrice().doubleValue());
viewHolder.getProduzer().setText(products.get(position).getManufacturer());
viewHolder.getProductName().setText(products.get(position).getName());
viewHolder.getPriceNumber().setText(price);
}
#Override
public int getItemCount() {
return products.size();
}
}
product_list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/productlist_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical" />
product_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="#+id/listLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="7dp"
tools:ignore="MissingConstraints">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/produzer"
android:layout_width="201dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Hoi"
/>
<TextView
android:id="#+id/productName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hoisss"
android:textStyle="bold"
android:textSize="16dp"
/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/priceNumber"
android:text="HoiNumber"
android:gravity="center"
android:textAlignment="textEnd"
android:textSize="20dp"
tools:ignore="RtlCompat" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MusicStoreService is an interface which is implemented in MusicStoreServiceMock.
The error from Logcat:
android.view.InflateException: Binary XML file line #2 in at.hlpinkafeld.android.musicstore:layout/product_list_fragment: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{f251fbc VFED.V... ......I. 0,0-0,0 #7f0901ed app:id/productlist_recycler}, adapter:null, layout:null, context:at.hlpinkafeld.android.musicstore.MainActivity#c57a6e8
Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{f251fbc VFED.V... ......I. 0,0-0,0 #7f0901ed app:id/productlist_recycler}, adapter:null, layout:null, context:at.hlpinkafeld.android.musicstore.MainActivity#c57a6e8
at androidx.recyclerview.widget.RecyclerView.generateLayoutParams(RecyclerView.java:4514)
at android.view.LayoutInflater.inflate(LayoutInflater.java:673)
at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
at at.hlpinkafeld.android.musicstore.fragments.ProductListFragment.onCreateView(ProductListFragment.java:32)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1899)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1823)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1760)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2985)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1455)
at android.app.Activity.performStart(Activity.java:8076)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3660)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
I really apperiate any help or an explaination why the way I have it now won't work.
Any help is really apperiated.

How to create a transparent toolbar and status bar and overlay an image for this class?

I have an xml layout file called fragment_about_sl.xml and the class associated to that called aboutSLFragment.java which is extended to fragment.java. Anyway all I want to do is make the toolbar transparent and overlay the image for this class only.I am new to android, so please help.
fragment_about_sl.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/aboutslscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.navigationdrawerfragments.aboutSLFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="250dp" />
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/viewPager"
android:layout_marginBottom="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
aboutSlFragment.java
public class aboutSLFragment extends Fragment{
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
TextView aboutsltext;
Button readmorebtn;
public aboutSLFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_sl, container,
false);
viewPager = (ViewPager) rootView .findViewById(R.id.viewPager);
sliderDotspanel = (LinearLayout)rootView.findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getContext(),
R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
aboutsltext=(TextView)rootView.findViewById(R.id.aboutsltext);
readmorebtn=(Button)rootView.findViewById(R.id.readmorebtn);
readmorebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (readmorebtn.getText().toString().equalsIgnoreCase("Read More"))
{
aboutsltext.setMaxLines(Integer.MAX_VALUE);//your TextView
readmorebtn.setText("Read Less");
}
else
{
aboutsltext.setMaxLines(3);//your TextView
readmorebtn.setText("Read More");
}
}
});
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments
different titles
getActivity().setTitle("About Sri Lanka");
}
I want my app to be like this
You can do that in onResume of that fragment:
#Override
public void onResume() {
super.onResume();
AppCompatActivity activity = (AppCompatActivity) getActivity();
ActionBar actionBar = activity.getSupportActionBar();
actionBar.hide();
}

Adding GridView for TabAcitivty fragments

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

Resize text size of a TextView in a Fragment

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

How to replace fragment run time

I want to add and replace Frame layout with fragment on fragment-1 and fragment-2 on item click of Grid and List item.
I had created main.xml class
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment1" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#000000" />
<fragment
android:id="#+id/fragment2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment2" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="fill_parent"
android:background="#000000" />
<FrameLayout
android:id="#+id/fragment3"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"/>
Here is my fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<GridView
android:id="#+id/Grid1"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:layout_height="0dp"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
and here is my row_fragment1_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="15dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#CCCCCC"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
and fragment_3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_fragment3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:text="This is 3rd Fragment" />
and here is my Main.xml
public class Main extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and here is Fragment1.class
public class Fragment1 extends Fragment implements OnItemClickListener
{
Activity myActivity;
GridView mGridView;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 7"};
private int imgID[] = {R.drawable.admin_access_rule,
R.drawable.admin_backup,R.drawable.admin_browsesite,
R.drawable.admin_comment_post,R.drawable.admin_content,
R.drawable.admin_content_type,R.drawable.admin_logout,};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_1,container, false);
mGridView = (GridView)view.findViewById(R.id.Grid1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart()
{
super.onStart();
mGridView.setAdapter(new GridBaseAdapter(myActivity));
mGridView.setOnItemClickListener(this);
}
private class GridBaseAdapter extends BaseAdapter
{
LayoutInflater mLayoutInflater = null;
public GridBaseAdapter(Context mContext)
{
mContext = myActivity;
mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public int getCount()
{
return ListItem.length;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return ListItem.length;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = mLayoutInflater.inflate(R.layout.row_fragment_list, null);
}
ImageView mImageView = (ImageView) convertView.findViewById(R.id.img_view);
mImageView.setImageResource(imgID[position]);
TextView tvUserEmail = (TextView) convertView.findViewById(R.id.text2);
tvUserEmail.setText("Sub " +ListItem[position]);
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("1st Fragment's : " + position +" Item Clicked");
}
}
My Fragment2.class
public class Fragment2 extends ListFragment
{
Activity myActivity;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 6","Item 7"};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
/** Creating an array adapter to store the list of countries **/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,ListItem);
/** Setting the list adapter for the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Toast.makeText(myActivity.getApplicationContext(), position +" Item Clicked", Toast.LENGTH_SHORT).show();
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("2nd Fragment's : " + position +" Item Clicked");
super.onListItemClick(l, v, position, id);
}
}
And Last my Fragment3.class
public class Fragment3 extends Fragment
{
Activity myActivity;
TextView txt_view;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_3,container, false);
txt_view = (TextView)view.findViewById(R.id.tv_fragment3);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
}
Make fragments expose interface that your activity can attach itself to. The event should occur when desired (e.g. list item is clicked). Then, activity should place instance of the fragment where it should be, for example:
// fragment is an instance of the fragment you want to show
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment3, fragment);
transaction.commit();

Categories