Android Fragment with RecyclerView not firing up click event - android

i am struggling since days to figure out why my click event is not firing up on items on a RecylerView.
i have the main Activity that uses a ViewPagerAdapter to show 4 fragments , one of the fragments uses a RecyclerView and an adapter to show items ( from Volley request ).
WelcomeActivity ---> ViewPagerAdapter ----> SearchListFragment ---> ProListAdapter
WelcomeActivity :
public class WelcomeActivity extends AppCompatActivity {
//View
private BottomNavigationView navigation;
//viewPager
private ViewPager viewPager;
private ViewPagerAdapter mViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
//Views
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
navigation.setSelectedItemId(0);
viewPager = findViewById(R.id.view_pager);
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mViewPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
navigation.getMenu().findItem(R.id.navigation_home).setChecked(true);
break;
case 1:
navigation.getMenu().findItem(R.id.navigation_search).setChecked(true);
break;
case 2:
navigation.getMenu().findItem(R.id.navigation_favorites).setChecked(true);
break;
case 3:
navigation.getMenu().findItem(R.id.navigation_settings).setChecked(true);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
break;
case R.id.navigation_favorites:
viewPager.setCurrentItem(2);
break;
case R.id.navigation_search:
viewPager.setCurrentItem(1);
break;
case R.id.navigation_settings:
viewPager.setCurrentItem(3);
break;
}
return false;
}
};
}
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ProfessionalListFragment();
case 1:
return new SearchListFragment();
case 2:
return new FavoritesFragment();
case 3:
return new SettingsFragment();
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
SearchListFragment :
public class SearchListFragment extends Fragment{
View rootView;
private RecyclerView recyclerView;
private ProListAdapter adapter;
ProgressDialog progressDialog;
String url;
String prof;
ArrayList<User> pros = new ArrayList<>();
public SearchListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Implementing View Pager
rootView = inflater.inflate(R.layout.fragment_search_list, container, false);
//RecyclerView
recyclerView = rootView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(rootView.getContext(), 3));
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
url = getArguments().getString("url");
prof = getArguments().getString("pro");
sendRequest();
}
}
private void sendRequest() {
//Show ProgressDialog
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle(getString(R.string.loading));
progressDialog.setMessage(getString(R.string.dialog_wait));
progressDialog.show();
Map<String, String> params = new HashMap();
params.put("prof", prof);
StringRequest jsonObjReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Response OK
....
adapter = new ProListAdapter(pros, getContext());
recyclerView.setAdapter(adapter);
....
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error
progressDialog.dismiss();
}
}){
#Override
protected Map<String, String> getParams()
{
return params;
}
};
//Adding the request to the queue along with a unique string tag
MySingleton.getInstance(getContext()).addToRequestQueue(jsonObjReq);
}
}
fragment_search_list.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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".WelcomeActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
tools:listitem="#layout/pro_card"/>
</LinearLayout>
ProListAdapter :
public class ProListAdapter extends RecyclerView.Adapter<ProListAdapter.ViewHolder>{
private ArrayList<User> itemsData;
private Context context;
public ProListAdapter(ArrayList<User> itemsData, Context context) {
this.itemsData = itemsData;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.pro_card, parent, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(context, itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.nom.setText(itemsData.get(position).getName());
holder.phone.setText(Long.toString(itemsData.get(position).getPhone()));
holder.img.setImageResource(R.drawable.avatar);
holder.card.setAnimation(AnimationUtils.loadAnimation(context, R.anim.zoom_in));
}
#Override
public int getItemCount() {
return itemsData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView nom, phone;
public ImageView img;
public CardView card;
private Context context;
public ViewHolder(Context context, View itemLayoutView) {
super(itemLayoutView);
card = itemLayoutView.findViewById(R.id.card_pro);
nom = itemLayoutView.findViewById(R.id.pro_nom);
phone = itemLayoutView.findViewById(R.id.pro_phone);
img = itemLayoutView.findViewById(R.id.pro_img);
this.context = context;
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
if (position != RecyclerView.NO_POSITION) {
Toast.makeText(context, "hi", Toast.LENGTH_LONG).show();
}
}
}
}
pro_card.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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="wrap_content"
android:layout_height="wrap_content"
android:clickable="true">
<androidx.cardview.widget.CardView
android:id="#+id/card_pro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:cardCornerRadius="8dp"
app:cardElevation="8dp"
android:background="#color/color_white">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/pro_img"
android:layout_width="140dp"
android:layout_height="130dp"
android:scaleType="centerInside"
android:src="#drawable/avatar"
android:background="?attr/selectableItemBackgroundBorderless"
app:layout_constraintBottom_toTopOf="#id/pro_nom"
app:layout_constraintStart_toStartOf="parent"
android:focusableInTouchMode="false"
android:clickable="false"/>
<TextView
android:id="#+id/pro_nom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="26sp"
app:layout_constraintBottom_toTopOf="#id/pro_phone"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="3dp"
tools:text="#tools:sample/first_names"
android:focusableInTouchMode="false"
android:clickable="false"/>
<TextView
android:id="#+id/pro_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:textColor="#000000"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="3dp"
tools:text="#tools:sample/us_phones"
android:focusableInTouchMode="false"
android:clickable="false"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
I tried many options but none is working , what is the best way and where is my mistake ?

Related

getItem function calling twice in FragmentStatePagerAdapter?

I Have a problem with getItem() function why because it is called twice in FragmentStatePagerAdapter class.
Actually the main reason is in application having TextoSpeech functionality so getItem() function twice the text also speech twice. This is my code can u please assist me....Great thanks in advance.
Here is the code
This is MainActivity class:
public class MainActivity extends FragmentActivity{
PagerFragment pagerFragment;
Cursor mCursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rhymes_activity_main);
DBUtils utils = new DBUtils(getApplicationContext());
new DBUtils(getApplicationContext());
try {
DBUtils.createDatabase();
} catch (IOException e) {
Log.w(" Create Db "+e.toString(),"===");
}
DBUtils.openDatabase();
mCursor = utils.getResult("select * from Cflviewpagerdata order by title");
final ArrayList<PageData> myList = new ArrayList<PageData>();
while (mCursor.moveToNext()) {
myList.add(new PageData(mCursor.getInt(
mCursor.getColumnIndex("_id")),
mCursor.getString(mCursor.getColumnIndex("title")),
mCursor.getString(mCursor.getColumnIndex("view"))));
}
mCursor.close();
ListView lv = (ListView) findViewById(R.id.list_view);
ListViewAdapter lva = new ListViewAdapter(this, R.layout.list_item, myList);
lv.setAdapter(lva);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//peace of code that create launch new fragment with swipe view inside
PagerFragment pagerFragment = new PagerFragment();
Bundle bundle = new Bundle();
bundle.putInt("CURRENT_POSITION", position);
bundle.putParcelableArrayList("DATA_LIST", myList);
pagerFragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.container, pagerFragment, "swipe_view_fragment").commit();
}
});
DBUtils.closeDataBase();
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
Fragment f = fm.findFragmentByTag("swipe_view_fragment");
if(f!=null){
fm.beginTransaction().remove(f).commit();
}else{
super.onBackPressed();
}
}
}
This is PagerFragment class:
public class PagerFragment extends Fragment{
private ArrayList<PageData> data;
private int currentPosition;
private String mTitle;
private FragmentActivity context;
#Override public void onAttach(Activity activity) {
context = (FragmentActivity) activity;
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager, container, false);
ViewPager mViewPager = (ViewPager) v.findViewById(R.id.pager_view);
currentPosition = getArguments().getInt("CURRENT_POSITION");
mTitle = getArguments().getString("T_TITLE");
data = getArguments().getParcelableArrayList("DATA_LIST");
FragmentItemPagerAdapter fragmentItemPagerAdapter = new FragmentItemPagerAdapter(getFragmentManager(), data);
mViewPager.setAdapter(fragmentItemPagerAdapter);
mViewPager.setCurrentItem(currentPosition);
return v;
}
}
This is FragmentItemPagerAdapter class:
public class FragmentItemPagerAdapter extends FragmentStatePagerAdapter{
private static ArrayList<PageData> data;
public FragmentItemPagerAdapter(FragmentManager fm, ArrayList<PageData> data){
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putString(PageFragment.TITLE, data.get(position).getTitle());
args.putString(PageFragment.DESCRIPTION, data.get(position).getDes());
args.putInt("CURRENT_POSITION", position);
fragment.setArguments(args);
return fragment;
}
void deletePage(int position) {
if (canDelete()) {
data.remove(position);
notifyDataSetChanged();
}
}
boolean canDelete() {
return data.size() > 0;
}
#Override
public int getItemPosition(Object object) {
// refresh all fragments when data set changed
return PagerAdapter.POSITION_NONE;
}
#Override
public int getCount() {
return data.size();
}
public static class PageFragment extends Fragment implements OnInitListener{
public static final String TITLE = "title";
public static final String DESCRIPTION = "view";
String om;
TextToSpeech tts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item, container, false);
((TextView) rootView.findViewById(R.id.item_label)).setText(getArguments().getString(TITLE));
View tv = rootView.findViewById(R.id.item_des);
((TextView) tv).setText(getArguments().getString(DESCRIPTION));
Bundle bundle = getArguments();
int currentPosition = bundle.getInt("CURRENT_POSITION");
tts = new TextToSpeech( getActivity(), PageFragment.this);
om = data.get(currentPosition).getDes();
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
return rootView;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
This is PageData class:
This class is Object class
public class PageData implements Parcelable{
private String title;
private String view;
public PageData(){
}
public PageData(Parcel in){
title = in.readString();
view = in.readString();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(view);
}
public PageData(int picture, String title, String description){
this.title = title;
this.view = description;
}
public String getTitle() {
return title;
}
public String getDes() {
return view;
}
}
This is Xml code
fragment_item.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="wrap_content"
android:padding="8dp"
android:orientation="vertical">
<TextView
android:id="#+id/item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
<TextView
android:id="#+id/item_des"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10sp"
android:text="Image Name"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_gravity="center_horizontal" />
</LinearLayout>
This is fragment_pager.xml: This is viewpager layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<android.support.v4.view.ViewPager
android:id="#+id/pager_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
This is rhymes_activity_main.xml: This is for listview of application.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:scrollbarAlwaysDrawVerticalTrack="true"
android:id="#+id/list_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
This images are my application look
This image is logcat of my application
Highlighted is my problem.
This is my code can you please help me any one.
I am new one of Android so please help
FragmentStatePagerAdapter preloads always at least 1 page.
You can try to use setUserVisibleHint to handle your logic only for visible fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Your code
}
}

How do I pass data between recyclerview and many fragments

Hi I have a simple app that features a recyclerView with list items (each representing a "employee" object
i use this tuto https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/ using tabhost but when i click in item recycler view i want to pass some data in one of tabs
recycler view item ===> to fragment
this is xml fragment
<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"
tools:context="com.example.iset.tse.Employee.OneFragment">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="92dp"
android:text="Information de contact :"
android:textColor="?android:attr/statusBarColor"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintHorizontal_bias="0.312"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/name_emp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="26dp"
android:text="username"
app:layout_constraintHorizontal_bias="0.204"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</android.support.constraint.ConstraintLayout>
code Java
public class OneFragment extends Fragment
{
TextView txt_name;
public OneFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
txt_name=(TextView) txt_name.findViewById(R.id.name_emp);
String name = getArguments().getString("name");
txt_name.setText(name);
return inflater.inflate(R.layout.fragment_one, container, false);
}
public static OneFragment newInstance(String nameValue) {
String name;
Bundle args = new Bundle();
OneFragment fragment = new OneFragment();
name = nameValue;
fragment.setArguments(args);
return fragment;
}
Activity 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"
tools:context="com.example.iset.tse.Employee.Details_Employee">
<View
android:id="#+id/view"
android:layout_width="421dp"
android:layout_height="211dp"
android:background="#1ABC9C"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.0" />
<ImageView
android:id="#+id/imageView9"
android:layout_width="70dp"
android:layout_height="57dp"
app:srcCompat="#drawable/employee"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="105dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.53" />
<TextView
android:id="#+id/name_emp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAlignment="center"
android:textAllCaps="false"
android:textStyle="bold|italic"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/imageView9" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="0dp"
android:layout_height="69dp"
android:background="#color/wallet_bright_foreground_holo_dark"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/view"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="0dp"
android:layout_height="541dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tabs">
</android.support.v4.view.ViewPager>
</android.support.constraint.ConstraintLayout>
java activity code
//tabs
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
/* Date_sys = (TextView) findViewById(R.id.date_sys);
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
Date_sys.setText(currentDateTimeString);
chechk_in.setText(chechkin);
*/
}
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabOne.setText("ONE");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_info, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
tabTwo.setText("TWO");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_time, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new OneFragment(), "ONE");
adapter.addFrag(new TwoFragment(), "TWO");
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
String name;
public void sendData(String nameAdapter) {
name = nameAdapter;
if (name != null) {
OneFragment med_frag = OneFragment.newInstance(name);
getSupportFragmentManager().beginTransaction()
.replace(R.id.viewpager, med_frag)
.commit();
}
}
this is My adapter
public class EmployeeAdapter extendsRecyclerView.Adapter<EmployeeAdapter.EmployeeHolder> {
final List<Employee> EmployeeList;
private Context context;
#Override
public EmployeeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row =
LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_row,parent,false);
EmployeeHolder holder= new EmployeeHolder(row);
return holder;
}
public EmployeeAdapter(List<Employee> EmployeeList) {
this.EmployeeList=EmployeeList;
}
#Override
public void onBindViewHolder(EmployeeHolder holder, int position) {
Employee employee=EmployeeList.get(position);
// holder.id.setText(employee.getId());
holder.name.setText(employee.getName());
}
#Override
public int getItemCount()
{
return EmployeeList.size();
}
public class EmployeeHolder extends RecyclerView.ViewHolder
{
private final Context context;
TextView name;
public EmployeeHolder(View itemView) {
super(itemView);
context = itemView.getContext();
name=(TextView)itemView.findViewById(R.id.name_emp);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Details_Employee)context).sendData(name.getText().toString());
}
So what you require is a model class for your data and sharing of data from one fragment to another.
You can share data using ArrayList(of your model class) as the argument for 2nd fragment from the first one and getting that ArrayList in your constructor.
eg: frag A and frag B and a model class named model.
Firstly a model class to store all your data eg
model class
public class model{
private String item1,item2,item3;
private int a,b,c;
public model(String item1, String item2, String item3, int a, int b, int c) {
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
this.a = a;
this.b = b;
this.c = c;
}
public String getItem1() {
return item1;
}
public void setItem1(String item1) {
this.item1 = item1;
}
public String getItem2() {
return item2;
}
public void setItem2(String item2) {
this.item2 = item2;
}
public String getItem3() {
return item3;
}
public void setItem3(String item3) {
this.item3 = item3;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public int getC() {
return c;
}
public void setC(int c) {
this.c = c;
}
}
Now in
frag A
public class frag_A extends Fragment {
private RecyclerView mRecyclerView;
MainAdapter mAdapter;
ArrayList<model> data_list;//DEFINE AN ARRAYLIST OF YOUR MODEL CLASS
public frag_A() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_frag_A, container, false);
mRecyclerView = (RecyclerView)v.findViewById(R.id.recyclerview_service);
data_list = new ArrayList<>();
//THIS IS WHERE MODEL CLASS IS USED TO SET DATA IN ARRAYLIST
model new_data=new model(item1,item2,item3,a,b,c);
data_list.add(model);//add the model data to your arraylist
mAdapter = new MainAdapter(data_list);//SET ARRAYLIST IN ADAPTER
//set all recyclerview components you want
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setAdapter(mAdapter);
//onclicklistener for recyclerview items
mRecyclerView.addOnItemTouchListener(
new mehakmeet.startup.com.v1.home.room_services.food_order.Adapter.RecyclerItemClickListener(getActivity().getApplicationContext(), new mehakmeet.startup.com.v1.home.room_services.food_order.Adapter.RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
//THIS IS THE PLACE WHERE DATA IS SHARED
service_details hk = new service_details(data_list);
//YOU CAN SHARE THE POSITION CLICKED HERE using bundle
Bundle args=new Bundle();
args.putString("position",String.valueOf(position);
hk.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main_home, hk).addToBackStack(null)
.commit();
}
})
);
return v;
}
}
Now to get that arraylist parameter , implement this arraylist in your frag_B constructor
frag_B
public class frag_B extends Fragment {
ArrayList<model> data_list;//Again define an arraylist of your model class
TextView item1,item2,item3
int a,b,c;
Button make_book;
//This is the constructor that uses the arraylist from previous fragment and can be used as arraylist in this fragment.
public frag_B(ArrayList<model> data_list) {
this.data_list=data_list;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_service_details, container, false);
item1=(TextView)v.findViewById(R.id.item_1);
item2=(TextView)v.findViewById(R.id.item_2);
item3=(TextView)v.findViewById(R.id.item_3);
//HERE GET THE POSITION CLICKED HERE
int position=Integer.parseInt(getArguments().getString("position");
item1.setText(data_list.get(position).getitem1());
item2.setText(data_list.get(position).getitem2());
item3.setText(data_list.get(position).getitem3());
a=data_list.get(position).getA();
b=data_list.get(position).getB();
c=data_list.get(position).getC();
return v;
}
}
You can use EventBus for that. Checkout the readme for how to use it.

Adapter not attach skipping layout

I am getting an error saying no adapter attach skipping layout.and the list doesn't appear in when emulator runs.please help.I cant see anything in list.screen appears blank.other items in the activity are appearing.i have seen almost all answer on the internet but didn't get any solution .and also when i tried to make a listview in other tab i got the list.
this is songsTab Activity
public class SongsTab extends Fragment {
private ArrayList<songInfo> songs = new ArrayList<songInfo>();
RecyclerView recyclerView;
SeekBar seekBar;
songAdapter songAdapter1;
MediaPlayer mediaPlayer;
Cursor cursor;
private Handler myHandler = new Handler();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.songs, container, false);
recyclerView = (RecyclerView)v. findViewById(R.id.recyclerView);
seekBar = (SeekBar) v.findViewById(R.id.seekBar);
songAdapter1 = new songAdapter(songs, getActivity());
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(songAdapter1);
solved();
checkUserPermission();
Thread t = new runThread();
t.start();
return v;
}
public void solved() {
songAdapter1.setOnitemClickListener(new songAdapter.OnitemClickListener() {
#Override
public void onItemclick(songAdapter.ViewHolder holder, View v, final songInfo obj, int position) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} else {
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongPath());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
Log.d("Prog", "run: " + mediaPlayer.getDuration());
}
});
} catch (Exception e) {
}
}
};
myHandler.postDelayed(runnable, 100);
}
}
});
}
public class runThread extends Thread {
#Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Runwa", "run: " + 1);
if (mediaPlayer != null) {
seekBar.post(new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
});
Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
}
}
}
}
private void checkUserPermission(){
if(Build.VERSION.SDK_INT>=23){
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},123);
return;
}
}
loadSongs();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 123:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
loadSongs();
}else{
Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void loadSongs(){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC+"!=0";
cursor = getContext().getContentResolver().query(uri,null,selection,null,null);
if(cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String SongPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
songInfo s = new songInfo(name, artist, SongPath);
songs.add(s);
} while (cursor.moveToNext());
}
cursor.close();
songAdapter1 = new songAdapter(songs, getActivity());
}
}
}
this is my Adapter
public class songAdapter extends RecyclerView.Adapter<songAdapter.ViewHolder> {
ArrayList<songInfo> songs;
Context context;
OnitemClickListener onitemClickListener;
public songAdapter(ArrayList<songInfo> songs, Context context) {
this.songs = songs;
this.context = context;
}
public interface OnitemClickListener{
void onItemclick(ViewHolder holder, View v, songInfo obj, int position);
}
public void setOnitemClickListener(OnitemClickListener onitemClickListener)
{
this.onitemClickListener=onitemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mView= LayoutInflater.from(context).inflate(R.layout.card,parent,false);
return new ViewHolder(mView);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final songInfo song = songs.get(position);
holder.songName.setText(songs.get(position).getSongName());
holder.artistName.setText(songs.get(position).getArtistName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onitemClickListener!=null)
{
onitemClickListener.onItemclick(holder,view,song,position);
}
}
});
}
#Override
public int getItemCount() {
return songs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView songName,artistName;
public ViewHolder(View itemView) {
super(itemView);
songName=(TextView)itemView.findViewById(R.id.songName);
artistName=(TextView)itemView.findViewById(R.id.artistName);
}
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
public ViewPagerAdapter pagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
private TabLayout tabLayout;
public static View rootView;
public static int tabNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.setAdapter(pagerAdapter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabNo = tab.getPosition();
mViewPager.setCurrentItem(tabNo);//setting current selected item over viewpager
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View rootView;
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.songs, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.album, container, false);
break;
}
case 3: {
rootView = inflater.inflate(R.layout.genres, container, false);
break;
}
case 4: {
rootView = inflater.inflate(R.layout.artist, container, false);
break;
}
}
return rootView;
}
}
}
recyclerView xml
<?xm 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"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/recyclerView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/seekBar" />
</ScrollView>
<SeekBar
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/seekBar"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="37dp"
android:indeterminate="false" />
</RelativeLayout>
this is cardView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="#f5fffa"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/songName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Shape of you"
android:maxLines="1"/>
<TextView
android:id="#+id/artistName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Ed Sheeran"
android:maxLines="1"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
mainActivity xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.murarilal.musicmania.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Don't initialize songAdapter1 again inside loadSongs().
Create a method like this in songAdapter class:
public void notifySongAdded(ArrayList<songInfo> songs) {
this.songs = songs;
notifyDataSetChanged();
}
And call songAdapter1.notifySongAdded(songs); after adding songs inside loadSongs().

image swiping not working in android view pager

I want to create an app which swipe images left/right so i use viewPager for this i run this code it gets run successfully but blank screen comes nothing happens.
This is my homeSwipe Class
public class homeSwipe extends Activity {
ViewPager viewPager;
customPagerAdapter customPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_swipe);
viewPager = (ViewPager) findViewById(R.id.pager);
customPagerAdapter = new customPagerAdapter(homeSwipe.this);
viewPager.setAdapter(customPagerAdapter);
}
}
that is my layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager 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/pager">
</android.support.v4.view.ViewPager>
</RelativeLayout>
This is my customPagerAdapter class
public class customPagerAdapter extends PagerAdapter {
private int imgres[] ={R.drawable.graypatternbackground,R.drawable.home,R.drawable.homescreen,R.drawable.redwall};
private Context context;
private LayoutInflater layoutInflater;
public customPagerAdapter(Context context){
this.context =context;
}
#Override
public int getCount() {
return imgres.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View item_view =(View)layoutInflater.inflate(R.layout.swipelayout,container,false);
ImageView imgView = (ImageView)item_view.findViewById(R.id.imageView);
imgView.setImageResource(imgres[position]);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
This is my swipelayout.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
</LinearLayout>
This is custompagerAdapter.
import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentStatePagerAdapter;public class PropTypePagerAdapter extends FragmentStatePagerAdapter { int noOfTab; public PropTypePagerAdapter(FragmentManager fm ,int noOfTab) { super(fm); this.noOfTab=noOfTab; } #Override public Fragment getItem(int position) { switch (position) { case 0: return new PropTabType(0); case 1: return new PropTabType(1); case 2: return new PropTabType(2); case 3: PropTabType service = new PropTabType(3); return service; } } #Override public int getCount() {
return noOfTab;
}
}
And this is logic for swapping image
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_prop_type_tab,container, false);fragImg = (ImageView) view.findViewById(R.id.fragImg); if (position == 0) { fragImg.setImageResource(R.drawable.buy); } else if (position == 1) { fragImg.setImageResource(R.drawable.rent1); } else { fragImg.setImageResource(R.drawable.hostel); } return view; }

Items of Navigation works in Emulator but not on my Device

after some modifications on my app, i can see that it works on abdroid studio emulator, the items in the navigation drawer are there, but when i install the app with apk on my mobile, i cant see the items but i can click on.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Accueil/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Accueil();
title = getString(R.string.title_accueil);
break;
case 1:
fragment = new NosOffres();
title = getString(R.string.title_nosoffres);
break;
case 2:
fragment = new ContactezNous();
title = getString(R.string.title_contact);
break;
case 3:
fragment = new Actualites();
title = getString(R.string.title_actu);
break;
case 4:
fragment = new MentionsLegales();
title = getString(R.string.title_mentions);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
TextView titlet;
titlet = (TextView) findViewById(R.id.main_toolbar_title);
titlet.setText(title);
titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
}
}
}
NavigationDrawerAdapter.java:
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
title.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/GothamBook.ttf"));
}
}
}
FragmentDrawer.java:
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
But i think the error is in the xml files, because i haven't touched the java class, but only xml layout files before the problem:
nav_drawer_row.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="50px"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textColor="#ffffff"
android:gravity="center_vertical"
android:textIsSelectable="false" />
</RelativeLayout>
activity_main.xml:
<android.support.v4.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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="fr.solutis.solutis.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
These 2 xml layour are in res/layout but i didn't do the same in res/layout-normal, but i think it's not a problem.
That was the height, it was so small ! So edit nav_drawer_row.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="150px"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textColor="#ffffff"
android:gravity="center_vertical"
android:textIsSelectable="false" />
</RelativeLayout>

Categories

Resources