Adapter not attach skipping layout - android

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().

Related

Android Fragment with RecyclerView not firing up click event

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 ?

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
}
}

can't see my cardView in tab layout

I want to show list of cardView in one of the tab of Tablayout, but when app runs tab appears blank. I am not getting the solution on the internet. There are four tabs in one of the tabs the list of cardView should appear, but emulator is showing blank activity.i m not getting any kind of content in tab.
This is my Mainactivity:
public class MainActivity extends AppCompatActivity {
private ViewPagerAdapter pagerAdapter;
private ViewPager mViewPager;
private Toolbar toolbar;
private TabLayout tabLayout;
#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);
mViewPager.setAdapter(pagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
Log.e("TAG", "TAB1");
break;
case 1:
Log.e("TAG", "TAB2");
break;
case 2:
Log.e("TAG", "TAB3");
break;
}
}
#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 = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.recyclerView);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
*/
}
}
this is the fragment
public class SongsTab extends Fragment {
RecyclerView recyclerView;
private ArrayList<songInfo> songs= new ArrayList<>();
songAdapter songAdapter;
MediaPlayer mediaPlayer;
SeekBar seekBar;
SeekBar seekBar2;
private int seekForwardTime = 5000;
private int seekBackwardTime = 5000;
Cursor cursor;
#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);
songAdapter = new songAdapter(songs, getContext());
recyclerView.setAdapter(songAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
mediaPlayer = new MediaPlayer();
songAdapter.setOnitemClickListener(new songAdapter.OnitemClickListener() {
#Override
public void onItemclick(final songAdapter.ViewHolder holder, View v, songInfo obj, int position) {
System.gc();
int songPath = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
cursor.moveToPosition(position);
final String filename = cursor.getString(songPath);
if (mediaPlayer.isPlaying()) {
// mediaPlayer.stop();
mediaPlayer.reset();
// mediaPlayer.release();
//mediaPlayer = null;
} else try {
/* Intent intent = new Intent( MainActivity.this, Main2Activity.class );
startActivity(intent);*/
try {
mediaPlayer.setDataSource(filename);
} catch (IOException e1) {
e1.printStackTrace();
}
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared (MediaPlayer mp){
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
mediaPlayer.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// });
// mediaPlayer.prepareAsync();
}
}
);
}catch(Exception e){
}
} ;
});
checkUserPermission();
return v;
}
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{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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 = getActivity().getContentResolver().query(uri,null,selection,null,null);
if(cursor != null){
if(cursor.moveToFirst()){
do{
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int songPath = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
songInfo s = new songInfo(name,artist,songPath);
songs.add(s);
}while (cursor.moveToNext());
}
// cursor.close();
songAdapter = new songAdapter(songs, getActivity());
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
cursor.close();
}
/*
public void nextSong() {
int currentPosition = mediaPlayer.getCurrentPosition();
// check if seekForward time is lesser than song duration
if(currentPosition + seekForwardTime <= mediaPlayer.getDuration()){
// forward song
mediaPlayer.seekTo(currentPosition + seekForwardTime);
}else{
// forward to end position
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}
*/
public void play(){
mediaPlayer.start();
}
}
this is xml mainactivity
<?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>
recycler view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView">
</android.support.v7.widget.RecyclerView>
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="60dp"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I have almost tried all the solution, but I'm not getting rid of this problem.
I can't see the part where you put a Fragment into your TabLayout. When the onTabSelected Event fires you should put your Fragment in the tab. If not, the tab is just empty.

How to change toolbar and tab color after CollapsingToolbarLayout?

I want to change the color of Collapsed Toolbar Layout(Red) to other color. How can I change that? I have given the image and my code sample below.I have tried to change through app:contentScrim="?attr/colorPrimary", but it not working. Thanks in advance.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/htab_collapse_toolbar"
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bgimage"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/htab_toolbar"
android:layout_width="match_parent"
android:layout_height="104dp"
android:gravity="top"
android:minHeight="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:titleMarginTop="13dp" />
<android.support.design.widget.TabLayout
android:id="#+id/htab_tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
app:tabIndicatorColor="#android:color/white" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/htab_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
Style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<!--<item name="colorAccent">#color/colorAccent</item>-->
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Parallax Tabs");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ViewPager viewPager = (ViewPager) findViewById(R.id.htab_viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.htab_tabs);
tabLayout.setupWithViewPager(viewPager);
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
collapsingToolbarLayout.setTitleEnabled(false);
ImageView header = (ImageView) findViewById(R.id.header);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ln);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#SuppressWarnings("ResourceType")
#Override
public void onGenerated(Palette palette) {
int vibrantColor = palette.getVibrantColor(R.color.colorPrimary);
int vibrantDarkColor = palette.getDarkVibrantColor(R.color.colorPrimaryDark);
collapsingToolbarLayout.setContentScrimColor(vibrantColor);
collapsingToolbarLayout.setStatusBarScrimColor(vibrantDarkColor);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
showToast("One");
break;
case 1:
showToast("Two");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(/*getResources().getColor(R.color.accent_material_light)*/), "CAT");
adapter.addFrag(new DummyFragment(/*getResources().getColor(R.color.ripple_material_light)*/), "DOG");
viewPager.setAdapter(adapter);
}
#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) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
static 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);
}
}
public static class DummyFragment extends Fragment {
int color;
SimpleRecyclerAdapter adapter;
public DummyFragment() {
}
#SuppressLint("ValidFragment")
public DummyFragment(int color) {
this.color = color;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dummy_fragment, container, false);
final FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.dummyfrag_bg);
//frameLayout.setBackgroundColor();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.dummyfrag_scrollableview);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
String text = "I am praveen";
adapter = new SimpleRecyclerAdapter(loadContentString());
recyclerView.setAdapter(adapter);
return view;
}
private String loadContentString() {
InputStream inputStream = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[8 * 1024];
int len;
String content = "";
try {
inputStream = getActivity().getAssets().open("lorem.txt");
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
content = outputStream.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeSilently(inputStream);
closeSilently(outputStream);
}
return content;
}
public void closeSilently(Closeable c) {
if (c == null) {
return;
}
try {
c.close();
} catch (Throwable t) {
// do nothing
}
}
}
}
SimpleRecyclerAdapter.java
public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleRecyclerAdapter.VersionViewHolder> {
String versionModels;
OnItemClickListener clickListener;
public SimpleRecyclerAdapter(String versionModels) {
this.versionModels = versionModels;
}
#Override
public VersionViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerlist_item, viewGroup, false);
VersionViewHolder viewHolder = new VersionViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(VersionViewHolder versionViewHolder, int i) {
versionViewHolder.title.setText(versionModels);
}
#Override
public int getItemCount() {
return 1;
}
class VersionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
TextView subTitle;
public VersionViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listitem_name);
}
#Override
public void onClick(View v) {
clickListener.onItemClick(v, getPosition());
}
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void SetOnItemClickListener(final OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
}
dummy_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dummyfrag_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<android.support.v7.widget.RecyclerView
android:id="#+id/dummyfrag_scrollableview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/cardview_light_background"/>
recyclerlist_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingBottom="8dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="8dp">
<TextView
android:id="#+id/listitem_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android version name"
android:textColor="#color/primary_text_default_material_light"
android:textSize="#dimen/abc_text_size_subhead_material" />
</LinearLayout>

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