The project is working fine, however the problem appeared when I add "switchPage2(new limits_fragmentpageC());" this is the logcat
Here is the code for BaseFlashCardsFragment
package com.flashcards;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Use the {#link BaseFlashCardsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BaseFlashCardsFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_POSITION = "position";
// TODO: Rename and change types of parameters
private int position;
private String mParam2;
public BaseFlashCardsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param position Parameter 1.
* #return A new instance of fragment BaseFlashCardsFragment.
*/
// TODO: Rename and change types and number of parameters
public static BaseFlashCardsFragment newInstance(int position) {
BaseFlashCardsFragment fragment = new BaseFlashCardsFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getInt(ARG_POSITION, 0);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = null;
int layoutId;
switch (position) {
case 0: layoutId = R.layout.limits_flashcardsfragment1; break;
case 1:layoutId = R.layout.limits_flashcardsfragment2; break;
case 2:layoutId = R.layout.limits_flashcardsfragment3; break;
default: layoutId = R.layout.limits_flashcardsfragment4;break;
}
rootView = inflater.inflate(layoutId, container, false);
rootView.findViewById(R.id.buttonterm).setOnClickListener(this);
rootView.findViewById(R.id.buttondefinition).setOnClickListener(this);
switchPage(new limits_fragmentpageA());
switchPage1(new limits_fragmentpageB());
switchPage2(new limits_fragmentpageC());
switchPage3(new limits_fragmentpageD());
return rootView;
}
#Override
public void onClick(View view) {
int viewId = view.getId();
if (viewId == R.id.buttonterm) {
switchPage(new limits_fragmentpageA());
}
else if (viewId == R.id.buttondefinition) {
switchPage(new limits_fragmentpageAA());
}
if (viewId == R.id.buttonterm) {
switchPage1(new limits_fragmentpageB());
}
else if (viewId == R.id.buttondefinition) {
switchPage1(new limits_fragmentpageBB());
}
if (viewId == R.id.buttonterm) {
switchPage2(new limits_fragmentpageC());
}
else if (viewId == R.id.buttondefinition) {
switchPage2(new limits_fragmentpageCC());
}
if (viewId == R.id.buttonterm) {
switchPage3(new limits_fragmentpageD());
}
else if (viewId == R.id.buttondefinition) {
switchPage3(new limits_fragmentpageDD());
}
}
private void switchPage (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer1, fragment)
.commit();
}
private void switchPage1 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer2, fragment)
.commit();
}
public void switchPage2 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer3, fragment)
.commit();
}
private void switchPage3 (Fragment fragment){
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction()
.replace(R.id.activity_main_fragmentcontainer4, fragment)
.commit();
}
}
Here is the code for limits_fragmentpageC
package com.flashcards;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class limits_fragmentpageC extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
return inflater.inflate(R.layout.limits_fragment_flashcards_c, container, false);
}
}
Here is the XML Layout, this includes the activity_main_fragmentcontainer3
<?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="match_parent"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp">
<include layout="#layout/include_toolbar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_marginTop="10dp"
android:text="Title 3"
android:textSize="22sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="5dp"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/buttonterm"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Term"
android:layout_marginRight="5dp"
android:background="#drawable/button_background"
android:layout_weight="1"/>
<Button
android:id="#+id/buttondefinition"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:text="Definition"
android:background="#drawable/button_background"
android:layout_weight="1"/>
</LinearLayout>
<FrameLayout
android:id="#+id/activity_main_fragmentcontainer3"
android:layout_width="match_parent"
android:layout_height="270dp"
android:layout_marginTop="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:background="#drawable/framelayout_border">
</FrameLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="(Swipe to Navigate) \n (3 of 10 Cards)"
android:layout_marginTop="15dp"
android:textSize="20sp"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
<include layout="#layout/include_toolbarbottom" />
</RelativeLayout>
Use
getActivity().getSupportFragmentManager()
in place of
getFragmentManager()
I'm pretty sure this is causing your problem because I had the same log output recently when I used getFragmentManager().
While working with support library version of Fragment, you should always use getSupportFragmentManager().
first dont use this line more than once in your layout
xmlns:android="http://schemas.android.com/apk/res/android"
second you use support fragment so you need to use getSupportFragmentManager() from the activity but because you want to use fragment inside a fragment you need to use getchildfragmentmanager()
Related
I have a RecyclerView which correctly displays data gotten from an RSS feed when it is the sole object within the XML file, i.e. it is not nested in a parent or sharing a parent within another element. Conversely, when I try to do just that, the data does not display, and I instead receive the error 'RecyclerView: No adapter attached; skipping layout' in LogCat. I should mention that this RecyclerView is generated as part of a ListFragment.
The Fragment replaces a FrameLayout in ActivityMain.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#color/design_default_color_primary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="#ffff"/>
<!-- This one -->
<FrameLayout
android:id="#+id/main_fragment_target"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id= "#+id/nav_view"
android:layout_width= "wrap_content"
android:layout_height= "match_parent"
android:layout_gravity= "start"
android:fitsSystemWindows= "true"
app:menu= "#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
Which is performed by the following code in MainActivity.java
MainActivity.this.runOnUiThread(() -> {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ComponentListFragment componentListFragment = new ComponentListFragment(componentsList);
transaction.replace(R.id.main_fragment_target, componentListFragment);
transaction.commit();
});
As mentioned, the data loads just fine when I'm not messing with the RecycleView XML file, so I am doubtful that inserting the fragment is the problem. I'm just posting this for posterity.
So, MainActivity.java replaces the fragment with an instance of ComponentListFragment.java:
package com.example.mclean_ross_s2030507;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
/**
* A fragment representing a list of Items.
*/
public class ComponentListFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private ArrayList<ListComponent> components;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ComponentListFragment() {
}
public ComponentListFragment(ArrayList<ListComponent> components) {
this.components = components;
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static ComponentListFragment newInstance(int columnCount) {
ComponentListFragment fragment = new ComponentListFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_component_list_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(
new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation())
);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(linearLayoutManager);
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(components));
}
return view;
}
}
Which builds a RecyclerView and sets the adapter to MyItemRecyclerViewAdapter.java:
package com.example.mclean_ross_s2030507;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.mclean_ross_s2030507.databinding.FragmentComponentListBinding;
import com.example.mclean_ross_s2030507.placeholder.PlaceholderContent.PlaceholderItem;
import java.util.ArrayList;
/**
* {#link RecyclerView.Adapter} that can display a {#link PlaceholderItem}.
* TODO: Replace the implementation with code for your data type.
*/
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final ArrayList<ListComponent> mValues;
public MyItemRecyclerViewAdapter(ArrayList<ListComponent> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(FragmentComponentListBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Log.e("MyTag", String.valueOf(holder));
holder.mItem = mValues.get(position);
// holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).getTitle());
holder.itemView.setOnClickListener(view -> {
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// public final TextView mIdView;
public final TextView mContentView;
public ListComponent mItem;
public ViewHolder(FragmentComponentListBinding binding) {
super(binding.getRoot());
// mIdView = binding.itemNumber;
mContentView = binding.content;
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
Finally, this is the view (fragment_component_list_list.xml) I am trying to achieve, but which is causing the error:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
tools:viewBindingType="androidx.recyclerview.widget.RecyclerView"
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/list"
android:name="com.example.mclean_ross_s2030507.ComponentListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:context=".ComponentListFragment"
tools:listitem="#layout/fragment_component_list"
android:scrollbars="vertical"/>
</LinearLayout>
However, the same file with the following setup works just fine:
<androidx.recyclerview.widget.RecyclerView
tools:viewBindingType="androidx.recyclerview.widget.RecyclerView"
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/list"
android:name="com.example.mclean_ross_s2030507.ComponentListFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:context=".ComponentListFragment"
tools:listitem="#layout/fragment_component_list"
android:scrollbars="vertical"/>
Nested:
Not nested:
I'm aware that various solutions to this error are all over SO, but I'm yet to see any specifically answering my issue regarding the nesting of RecyclerView. As always, any help is much appreciated. Cheers.
The view being inflated in onCreateView of ComponentListFragment is not a RecyclerView but a LinearLayout, based on the contents of R.layout.fragment_component_list_list you provided. The parent View/ViewGroup is always returned from inflate. So you need to reference the actual RecyclerView inside of that layout:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_component_list_list, container, false);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.list)
// No need for if statement, just use `rv` variable...
...
Also, your XML has a few mistakes and areas for improvement:
Remove the redundant namespace (xmlns) attributes in the RecyclerView element and move xmlns:app to the root element.
The android:name attribute is only used in the <application> element of the AndroidManifest.xml
You don't need the tools:viewBindingType attribute. It's only needed to disambiguate generated views when using View Binding Type
tools:context is only meant for the root view. See tools attributes
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="#layout/fragment_component_list"
android:scrollbars="vertical"/>
</LinearLayout>
This is my first attempt to develop an android application.
I have a MainActivity with ConstraintLayout that has BottomNavigationView. Whenever the first navigation item is selected, I want to display a list of category (displayed in a fragment), then whenever this category is selected, another list will be displayed for items related to that particular category (in another fragment).
I have read in (Android - fragment .replace() doesn't replace content - puts it on top) it states that "static fragments written in XML are unable to be replaced, it has to be in a fragment container", how does it look like?
I tried to create my fragment container, but there is something wrong when I try to get the ListView (grand child of the container)
categoriesListView = getView().findViewById(R.id.categoriesList);
returns null.
MainActivity
package com.alsowaygh.getitdone.view.main;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.services.CategoriesListFragment;
import com.alsowaygh.getitdone.view.services.OnCategorySelectedListener;
import com.alsowaygh.getitdone.view.services.ServicesListFragment;
public class MainActivity extends AppCompatActivity implements OnCategorySelectedListener {
private static final String TAG = "MainActivity";
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.add(R.id.container, categoriesListFragment);
fragmentTransaction.commit();
return true;
case R.id.navigation_bookings:
// mTextMessage.setText(R.string.title_bookings);
return true;
case R.id.navigation_chats:
// mTextMessage.setText(R.string.title_chats);
return true;
case R.id.navigation_settings:
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
}
#Override
public void onCategorySelected(String category) {
Log.w(TAG, "Successfully created CategoryListFragment!");
}
}
activity_main layout
<?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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Fragment
package com.alsowaygh.getitdone.view.services;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.alsowaygh.getitdone.R;
import com.alsowaygh.getitdone.view.main.MainActivity;
public class CategoriesListFragment extends Fragment {
private ListView categoriesListView;
OnCategorySelectedListener categoryListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
//initializing root view first to refer to it
View rootView = inflater.inflate(R.layout.activity_main, container, false);
//initializing ListView
categoriesListView = getView().findViewById(R.id.categoriesList);
//categories list
final String[] categories = {"first category", "second category", "third category", "Fourth category"};
//initializing and adding categories strings to the addapter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this.getContext(),
R.layout.category_textview);
for (String c : categories) {
arrayAdapter.add(c);
}
categoriesListView.setAdapter(arrayAdapter);
//implement onListItemClick
categoriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//retrieve string from categories list at clicked position
categoryListener.onCategorySelected(categories[position]);
}
});
return rootView;
}
#Override //to fource container activity to implement the OnCategorySelectedListener
public void onAttach(Context context) {
super.onAttach(context);
try{
categoryListener = (OnCategorySelectedListener) context;
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "must implement OnCategorySelectedListener");
}
}
}
fragments container
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</fragment>
</FrameLayout>
Your help will be much appreciated.
You need to add the FrameLayout container within the layout file of the MainActivity(activity_main), onclick of the buttons in BottomNavigationView replace with the fragment. In this way you have a Activity and the fragments are shown within the activity, on click of each menu item you can invoke to replace it with the fragments.
This should resolve your problem.
You need to change the layout as below in activity_main.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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".view.main.MainActivity">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
In the MainActivity code, you need to change as below:
case R.id.navigation_services:
// mTextMessage.setText(R.string.title_services);
CategoriesListFragment categoriesListFragment = new CategoriesListFragment();
fragmentTransaction.replace(R.id.frame, categoriesListFragment);
fragmentTransaction.commit();
return true;
In the fragment layout file change to LinearLayout:
<LinearLayout
android:id="#+id/categories_list_fragment"
android:name="com.alsowaygh.getitdone.view.services.CategoriesListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp">
<ListView
android:id="#+id/categoriesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp" />
</LinearLayout>
EDIT
In the fragment code, change the layout to the name of the fragment layout file(R.layout.fragment_layout_name).
View rootView = inflater.inflate(R.layout.fragment_layout_name, container, false);
//initializing ListView
categoriesListView = rootView.findViewById(R.id.categoriesList);
I want to implement onclick in my fragment to change fragment.
Here is this function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
It's 'clicking' cause I hear the typical button sound. But i'm getting this error when clicks:
ssl=0xaf840c00 cert_verify_callback x509_store_ctx=0xa17d2280 arg=0x0
ssl=0xaf840c00 cert_verify_callback calling verifyCertificateChain authMethod=ECDHE_RSA
Here is my main_activity layout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarInner"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize">
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout android:id="#+id/content_frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#212"
android:layout_below="#+id/toolbar_app_bar_layout">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:id="#+id/toolbar_app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/top_points_bar" />
</LinearLayout>
<android.support.design.widget.TabLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
app:tabMode="scrollable"
app:paddingStart="16dp"
app:tabPaddingStart="16dp"
app:tabPaddingEnd="16dp"
app:tabMinWidth="96dp"
app:tabGravity="center" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<android.support.design.widget.NavigationView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#color/md_brown_100"
app:menu="#menu/menu_drawer"
android:textColor="#color/okurwa"
app:theme="#style/MyTabStyle"
app:headerLayout="#layout/nav_drawer_header"
app:itemTextAppearance="#style/MyTabTextStyle"
android:clipToPadding="false">
<TextView
android:id="#+id/nav_drawer_wallet_id"
android:layout_width="177dp"
android:layout_height="wrap_content"
android:textSize="15sp"
android:layout_marginTop="8dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"/>
<TextView
android:id="#+id/nav_drawer_total_credits"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:textSize="16sp"
android:layout_marginTop="200dp"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/nav_drawer_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="22sp"
android:layout_marginTop="150dp"/>
<!--<FrameLayout-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="bottom"-->
<!--android:background="#color/md_white_1000"-->
<!--android:elevation="4dp"-->
<!--android:layout_marginBottom="-96dp">-->
<!--<Button android:id="#+id/navigation_button_footer"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text=""-->
<!--android:textSize="13sp"-->
<!--android:textColor="#color/md_grey_800"-->
<!--android:lines="3"-->
<!--android:gravity="center"-->
<!--style="#style/Widget.AppCompat.ActionButton"-->
<!--android:paddingTop="20dp"-->
<!--android:paddingLeft="20dp"-->
<!--android:paddingRight="20dp"-->
<!--android:paddingBottom="20dp"/>-->
<!--</FrameLayout>-->
</android.support.design.widget.NavigationView>
<RelativeLayout
android:id="#+id/lay_connection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/actmain_margintop"
android:background="#3c3c3c"
android:visibility="gone" >
<TextView
android:id="#+id/text_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
<RelativeLayout
android:id="#+id/lay_dialog"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" >
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:text="#string/error_no_internet"
android:textColor="#color/md_white_1000"
android:textSize="#dimen/twentyfive" />
</RelativeLayout>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Please help me guys! I see this error first time. I don't know why I'm getting this error and why it's not working. Thanks Stack's Community!
EDIT
This is full code of this fragment:
/**
* Created by otsma on 12.12.2016.
*/
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import com.commonutility.PreferenceConnector;
import com.justfashion.R;
import java.util.Random;
public class OneFragment extends Fragment {
final Random rnd = new Random();
public OneFragment() {
// Required empty public constructor
}
private static TextView creditWallet;
private String[] myString;
private static final Random rgenerator = new Random();
private TextView firstName, textView13,textView14,textView15,textView16,textView17,textView18;
private Animation animShake, wbijam, load1, load2, load3, load4, load5, load6, wbijam1, wbijam2, wbijam3, wbijam4, wbijam5;
private ImageView img, imageView9,imageView19,imageView4,imageView5,imageView6,imageView7,imageView8;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public static void onUpdateView(Context aiContext) {
// TODO Auto-generated method stub
if (aiContext != null && creditWallet != null)
creditWallet.setText(PreferenceConnector.readInteger(aiContext, PreferenceConnector.WALLETPOINTS, 0) + "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
img = (ImageView)view.findViewById(R.id.imgRandom);
imageView4 = (ImageView)view.findViewById(R.id.imageView4);
imageView5 = (ImageView)view.findViewById(R.id.imageView5);
imageView6 = (ImageView)view.findViewById(R.id.imageView6);
imageView7 = (ImageView)view.findViewById(R.id.imageView7);
imageView8 = (ImageView)view.findViewById(R.id.imageView8);
firstName = (TextView)view.findViewById(R.id.imie);
textView13 = (TextView)view.findViewById(R.id.textView13);
textView14 = (TextView)view.findViewById(R.id.textView15);
textView15 = (TextView)view.findViewById(R.id.textView16);
textView16 = (TextView)view.findViewById(R.id.textView17);
textView17 = (TextView)view.findViewById(R.id.textView18);
textView18 = (TextView)view.findViewById(R.id.textView19);
final Animation wbijam = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView13.startAnimation(wbijam);
final Animation wbijam1 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView14.startAnimation(wbijam1);
final Animation wbijam2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView15.startAnimation(wbijam2);
final Animation wbijam3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView16.startAnimation(wbijam3);
final Animation wbijam4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView17.startAnimation(wbijam4);
final Animation wbijam5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.wbijam);
textView18.startAnimation(wbijam5);
final Animation animShake = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.shak);
img.startAnimation(animShake);
final Animation load2 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load2);
imageView4.startAnimation(load2);
final Animation load3 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load3);
imageView5.startAnimation(load3);
final Animation load4 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load4);
imageView6.startAnimation(load4);
final Animation load5 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load5);
imageView7.startAnimation(load5);
final Animation load6 = AnimationUtils.loadAnimation(getActivity().getApplicationContext(), R.anim.load6);
imageView8.startAnimation(load6);
firstName.setText("Hey,"+" " +PreferenceConnector.readString(getActivity().getApplicationContext(), PreferenceConnector.FIRST_NAME, ""));
// Inflate the layout for this fragment
final ImageView img = (ImageView) view.findViewById(R.id.imgRandom);
// return view;
// ^^^^ error remove it
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
String q = myString[rgenerator.nextInt(myString.length)];
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(q);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(9);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getActivity().getApplicationContext())
));
return view;
// ^^^ move it here
}
// I have 3 images named img_0 to img_2, so...
protected final static int getResourceID
(final String resName, final String resType, final Context ctx) {
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0) {
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
} else {
return ResourceID;
}
}
}
remove super.onViewCreated(view, savedInstanceState);
return your view
please return the view
retun view;
if the problem still persists
To Make Sure whether the problem is with Onclick or not, comment
Everything inside the onclick method and put a Toast inside it. so, i
think we could get a clear picture about the problem..
try this !!
replace the following line:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
to this:
android.app.FragmentTransaction transaction = getActivity().getFragmentManager().beginTransaction();
Also don't forget to return view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
super.onViewCreated(view, savedInstanceState);
imageView9 = (ImageView)view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
return view;
}
your fragment and fragment manager should be of same type.so either import
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
OR
import android.app.Fragment;
import android.app.FragmentTransaction;
java file
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
imageView9 = (ImageView) view.findViewById(R.id.imageView3);
imageView9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Create new fragment and transaction
Fragment newFragment = new FragEditProfile();
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, newFragment)
.addToBackStack(null)
.commit();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
});
// your other contents.....
return view;
}
You better implement Interface for click event like this
public class fragment_test extends Fragment implements View.OnClickListener {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
switch (v.getItemId()) {
case R.id.action_zoom_in:
// .....
break;
}
return true;
}
}
}
I have made a sliding menu like that of facebook by following the tutorial which is available in the following site:
http://www.devexchanges.info/2016/05/creating-your-own-sliding-menu-like.html?m=1
Now in the main layout I have added a long paragraph of text so in order to view everything I used ScrollView. But when I use ScrollView I cannot pull the menu out, I can only open the drawer by clicking on the button. Please help me on how to scroll through the para and also be able to pull the menu drawer.
The MainActivity XML file:
<info.devexchanges.slidingmenu.SlidingLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This holds our menu -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarmenu"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#102961"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ListView
android:id="#+id/activity_main_menu_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbarmenu"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<!-- This holds our content-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/toolbar"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:onClick="toggleMenu"
android:src="#drawable/menu" />
<TextView
android:id="#+id/title"
style="#style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:gravity="center"
android:textColor="#android:color/white" />
</android.support.v7.widget.Toolbar>
<!-- Fragments container layout -->
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
the_fiesta Fragment (the home Fragment) XML file:
<?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="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<ScrollView
android:layout_width="800dp"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fiesta_title"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_alignParentTop="true"
android:id="#+id/imageView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/the_fiesta"
android:id="#+id/textView"
android:textSize="17sp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="#+id/imageView"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</ScrollView>
Java file of MainActivity:
package info.devexchanges.slidingmenu;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// The SlidingLayout which will hold both the sliding menu and our main content
// Main content will holds our Fragment respectively
SlidingLayout slidingLayout;
// ListView menu
private ListView listMenu;
private String[] listMenuItems;
private Toolbar toolbar;
private TextView title; //page title
private ImageView btMenu; // Menu button
private Fragment currentFragment;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the mainLayout
setContentView(R.layout.activity_main);
slidingLayout = (SlidingLayout) findViewById(R.id.sliding_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
title = (TextView) findViewById(R.id.title);
setSupportActionBar(toolbar);
// Init menu
listMenuItems = getResources().getStringArray(R.array.menu_items);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listMenu = (ListView) findViewById(R.id.activity_main_menu_listview);
listMenu.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listMenuItems));
listMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onMenuItemClick(parent, view, position, id);
}
});
// handling menu button event
btMenu = (ImageView) findViewById(R.id.menu_icon);
btMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
// Replace fragment main when activity start
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
TheFiesta fragment = new TheFiesta();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
title.setText("The Fiesta");
}
public void toggleMenu(View v) {
slidingLayout.toggleMenu();
}
// Perform action when a menu item is clicked
private void onMenuItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment;
if (position == 0) {
fragment = new TheFiesta();
title.setText("The Fiesta");
} else if (position == 1) {
fragment = new ListViewFragment();
title.setText("Events");
} else if (position == 2) {
fragment = new TextViewFragment();
Bundle args = new Bundle();
args.putString("KEY_STRING", "This is a TextView in the Fragment");
fragment.setArguments(args);
title.setText("Schedule");
} else if (position == 3) {
fragment = new ListViewFragment();
title.setText("Schools");
} else if (position == 4) {
fragment = new ListViewFragment();
title.setText("Updates");
} else if (position == 5) {
fragment = new ListViewFragment();
title.setText("Our Team");
} /*else if (position == 6) {
fragment = new ListViewFragment();
title.setText("About Us");
}*/ else {
fragment = new DummyFragment();
title.setText("About Us");
}
if(!fragment.getClass().equals(currentFragment.getClass())) {
// Replace current fragment by this new one
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
}
// Hide menu anyway
slidingLayout.toggleMenu();
}
#Override
public void onBackPressed() {
if (slidingLayout.isMenuShown()) {
slidingLayout.toggleMenu();
} else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
getSupportActionBar().setTitle("");
}
}
try this instead of Fragments container. add this code below
</android.support.v7.widget.Toolbar> this may work.
<LinearLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:id="#+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView1" />
</LinearLayout>
</ScrollView>
</LinearLayout>
I have made an adapter of CardView through the RecyclerView for me to use the same template of card for this feature of mine.
The objective is to create certain cards with different colors, based on the parameter inc_status in INCCards.java. But it doesn't just seem to work.
Here's the source code for the template card:
item_inc_card.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/spacing_medium"
android:paddingRight="#dimen/spacing_medium"
android:paddingTop="#dimen/spacing_medium"
android:background="#color/tertiary">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="#dimen/spacing_none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_large"
android:paddingTop="#dimen/spacing_large"
android:paddingBottom="#dimen/spacing_medium"
android:id="#+id/relative_layout">
<TextView
android:id="#+id/course_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textColor="#color/white"
android:textSize="#dimen/text_headline"
android:text="#string/course_code"
android:textStyle="bold"/>
<TextView
android:id="#+id/course_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/course_code"
android:textColor="#color/white"
android:textSize="#dimen/text_subhead"
android:text="#string/course_title" />
<TextView
android:id="#+id/faculty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/white"
android:layout_below="#+id/course_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="italic"
android:textSize="#dimen/text_body"
android:text="#string/faculty" />
<ImageView
android:id="#+id/status_icon"
android:src="#drawable/icon_avatar"
android:layout_width="#dimen/size_user_icon"
android:layout_height="#dimen/size_user_icon"
android:layout_above="#+id/faculty"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/inc_grade"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_body"
android:layout_below="#+id/status_icon"
android:layout_alignRight="#+id/status_icon"
android:layout_alignEnd="#+id/status_icon"
android:layout_alignLeft="#+id/status_icon"
android:layout_alignStart="#+id/status_icon"
android:gravity="center"
android:textAlignment="center"
android:textColor="#color/white"
android:text="#string/equiv_grade"/>
</RelativeLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="0.001dp"
android:background="#FFFFFF"
android:id="#+id/line_divider"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_medium"
android:paddingBottom="#dimen/spacing_medium"
android:layout_marginTop="#dimen/spacing_medium"
android:id="#+id/semesterInfoLinearLayout">
<TextView
android:id="#+id/section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/section"
android:textColor="#color/white"
android:layout_weight="0.33" />
<TextView
android:id="#+id/semester"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/semester"
android:textColor="#color/white"
android:layout_weight="0.33"
android:gravity="center" />
<TextView
android:id="#+id/acad_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_caption"
android:text="#string/acad_year"
android:textColor="#color/white"
android:layout_weight=".33"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
And for the fragment layout:
item_inc_card.xml
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_inc_cards"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/tertiary"/>
To where each card is initialized by the object
INCCards.java
package ph.edu.amitypipduo.myiit;
public class INCCards {
String course_code, course_title, faculty, section, semester, acad_year;
int inc_status, status_icon;
final String inc_grade = "INC 3.00";
public INCCards(String course_code, String course_title, String faculty, String section, String semester, String acad_year, String inc_status) {
this.course_code = course_code;
this.course_title = course_title;
this.faculty = faculty;
this.section = section;
this.semester = semester;
this. acad_year = acad_year;
switch (inc_status) {
case "notice":
this.inc_status = R.color.inc_notice;
this.status_icon = R.drawable.inc_notice;
break;
case "alert":
this.inc_status = R.color.inc_alert;
this.status_icon = R.drawable.inc_alert;
break;
case "warning":
this.inc_status = R.color.inc_warning;
this.status_icon = R.drawable.inc_warning;
break;
case "danger":
this.inc_status = R.color.inc_danger;
this.status_icon = R.drawable.inc_danger;
break;
}
}
}
I tried setting the background color of the card at method onBindViewHolder by:
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
as seen here in
INCAdapter.java
package ph.edu.amitypipduo.myiit;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class INCAdapter extends RecyclerView.Adapter<INCAdapter.CardViewHolder> {
List<INCCards> inc_cards;
public INCAdapter(List<INCCards> inc_cards){
this.inc_cards = inc_cards;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_inc_card, viewGroup, false);
CardViewHolder card_view_holder = new CardViewHolder(view);
return card_view_holder;
}
#Override
public void onBindViewHolder(CardViewHolder cardViewHolder, int i) {
cardViewHolder.course_code.setText(inc_cards.get(i).course_code);
cardViewHolder.course_title.setText(inc_cards.get(i).course_title);
cardViewHolder.faculty.setText(inc_cards.get(i).faculty);
cardViewHolder.section.setText(inc_cards.get(i).section);
cardViewHolder.semester.setText(inc_cards.get(i).semester);
cardViewHolder.acad_year.setText(inc_cards.get(i).acad_year);
cardViewHolder.inc_grade.setText(inc_cards.get(i).inc_grade);
cardViewHolder.status_icon.setImageResource(inc_cards.get(i).status_icon);
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
}
#Override
public int getItemCount() {
return inc_cards.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class CardViewHolder extends RecyclerView.ViewHolder {
CardView card_view;
TextView course_code, course_title, faculty, section, semester, acad_year, inc_grade;
ImageView status_icon;
CardViewHolder(View itemView) {
super(itemView);
card_view = (CardView) itemView.findViewById(R.id.card_view);
course_code = (TextView) itemView.findViewById(R.id.course_code);
course_title = (TextView) itemView.findViewById(R.id.course_title);
faculty = (TextView) itemView.findViewById(R.id.faculty);
inc_grade = (TextView) itemView.findViewById(R.id.inc_grade);
section = (TextView) itemView.findViewById(R.id.section);
semester = (TextView) itemView.findViewById(R.id.semester);
acad_year = (TextView) itemView.findViewById(R.id.acad_year);
status_icon = (ImageView) itemView.findViewById(R.id.status_icon);
}
}
}
Then initializing the data in the fragment class and inflating the layout:
INCMonitorFragment.java
package ph.edu.amitypipduo.myiit;
import android.app.Activity;
import android.app.Fragment;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class INCMonitorFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RecyclerView recycler_view;
private LinearLayoutManager linear_layout_manager;
private INCAdapter inc_adapter;
private List<INCCards> inc_cards;
private void initializeData() {
inc_cards = new ArrayList<>();
inc_cards.add(new INCCards("CSC 198", "Methods of Research", "Prof. Cyrus Gabilla", "CS-1A", "SECOND SEMESTER", "AY 2014-2015", "danger"));
inc_cards.add(new INCCards("POLSCI 2", "Philippine Govt. & Const.", "Prof. Cyrus Gabilla", "AB4", "SUMMER SEMESTER", "AY 2013-2014", "warning"));
inc_cards.add(new INCCards("ENG 2N", "Writing in Discipline", "Prof. Rabindranath Polito", "B4", "FIRST SEMESTER", "AY 2012-2013", "alert"));
inc_cards.add(new INCCards("MATH 51", "I Forgot the Course Title", "Prof. Forgotten Name", "69", "SECOND SEMESTER", "AY 2012-2013", "notice"));
}
// TODO: Rename and change types and number of parameters
public static INCMonitorFragment newInstance(String param1, String param2) {
INCMonitorFragment fragment = new INCMonitorFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public INCMonitorFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
initializeData();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_inc_monitor, container, false);
recycler_view = (RecyclerView) view.findViewById(R.id.fragment_inc_cards);
recycler_view.setHasFixedSize(true);
linear_layout_manager = new LinearLayoutManager(getActivity().getApplicationContext());
recycler_view.setLayoutManager(linear_layout_manager);
inc_adapter = new INCAdapter(inc_cards);
recycler_view.setAdapter(inc_adapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
But it only shows this:
Why does it not recognize the color? How come the R.drawable..... was recognized by the onBindViewHolder and not the R.color.....?
Change
cardViewHolder.card_view.setCardBackgroundColor(inc_cards.get(i).inc_status);
to
int colorId = inc_cards.get(i).inc_status;
int color = cardViewHolder.card_view.getContext().getResources().getColor(colorId);
cardViewHolder.card_view.setCardBackgroundColor(color);
You are using the value from R.color instead of the value you set in your XML.
I'm getting a more reliable color overriding with this line:
setBackgroundTintList(ColorStateList.valueOf(color));
instead of:
setCardBackgroundColor(color).
One thing to add, make sure you have the alpha in your color number and if you don't just add ff at the begining of your color, otherwise it won't work correctly.
For example this works
view.setCardBackgroundColor(0xff2ecc71)
While this one shows a white background
view.setCardBackgroundColor(0x2ecc71)
Try to use Material Card View Instead
then Do something LIke this:
private MaterialCardView imgIgnition;
imgIgnition = findViewById(R.id.imgIgnition);
imgIgnition.setCardBackgroundColor(Color.parseColor("#198754"));