I have Pageradapter in which i have 3 fragments.
I have button on first fragment
what i want to achieve is open list of installed app with check box.
I have created activity which shows ListView with check box
I'm unable to open that activity.
MainActivity
package com.aditya.att;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
// Tab titles
//private String[] tabs = { "Setting", "Charts", "Usage", "Add" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Getting a reference to the ViewPager defined the layout file */
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
/** Getting fragment manager */
FragmentManager fm = getSupportFragmentManager();
/** Instantiating PagerAdapter */
PagerAdapter pAdapter = new PagerAdapter(fm);
/** Setting the pagerAdapter to the pager object */
viewPager.setAdapter(pAdapter);
/** Called when the user clicks the Send button */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
fragment AppSetting
package com.aditya.att;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.view.View;
public class AppSetting extends Fragment {
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), MyList.class);
startActivity(intent);
//getActivity().startActivity(intent);
}
}
Activity MyList
package com.aditya.att;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MyList extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// create an array of Strings, that will be put to our ListActivity
ArrayAdapter<Model> adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<Model> getModel() {
List<Model> list = new ArrayList<Model>();
list.add(get("Linux"));
list.add(get("Windows7"));
list.add(get("Suse"));
list.add(get("Eclipse"));
list.add(get("Ubuntu"));
list.add(get("Solaris"));
list.add(get("Android"));
list.add(get("iPhone"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private Model get(String s) {
return new Model(s);
}
}
Adapter InteractiveArrayAdapter
package com.aditya.att;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.rowbuttonlayout, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.rowbuttonlayout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) viewHolder.checkbox
.getTag();
element.setSelected(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
class Model
package com.aditya.att;
public class Model {
private String name;
private boolean selected;
public Model(String name) {
this.name = name;
selected = false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
activity_main
<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.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_tab_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:textColor="#fff"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_setting
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#5cdf06">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Setting add Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="66dp"
android:layout_marginTop="26dp"
android:drawableBottom="#drawable/btn_toggle_off"
android:text="Button"
android:onClick="sendMessage"/>
</RelativeLayout>
rowbuttonlayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="30px" >
</TextView>
<CheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="4px"
android:layout_marginRight="10px" >
</CheckBox>
</RelativeLayout>
PagerAdapter
package com.aditya.att;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
public Bundle data;
/** Constructor of the class */
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
switch (arg0) {
case 0:
AppSetting myFragment = new AppSetting();
/*data= new Bundle();
data.putInt("current_page", arg0+1);
myFragment.setArguments(data);*/
return myFragment;
case 1:
AppActivity myFragment1 = new AppActivity();
/*data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment1.setArguments(data);*/
return myFragment1;
}
AppSetting myFragment2 = new AppSetting();
/*data = new Bundle();
data.putInt("current_page", arg0+1);
myFragment2.setArguments(data);*/
return myFragment2;
}
/** Returns the number of pages */
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
// Top Rated fragment activity
return "Setting";
case 1:
// Games fragment activity
return "Usage";
case 2:
// Movies fragment activity
return "Actitvity";
case 3:
// Add fragment activity
return "Add";
}
return null;
}
}
there are two more fragments
1-AppActivity
1-AppUsage
but there is no code for them yet
I hope I have cleared everything.
mainactivity loads with pagertitlestrip---> on setting ---> click on button---> open activity list of installed app with check box.(used ListView as placeholder )
exact feature available in app lock where user is asked to select apps to lock.
Thank You
Intent intent = new Intent(getActivity(), Activity_name.class);
startActivity(intent);
Related
hello please I need help
I want to add an Edittext to use it for search for recycleview
my program will be run without crashing but it not work
in my project I have a BottomNavigation (fragment) and inside it I used Tablayout (fragment) (a fragment inside another fragment (Tab inside bottom navigation))
I have no error but my search is not working
**If It is possible for you , please add this code inside your new blank project and test it and help me **
I used this search totorial by this learning project
https://codinginflow.com/tutorials/android/searchview-recyclerview
My Main Activity code is(Fragment of BottomNavigation is inside MainActicity)
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
FrameLayout frameLayout;
//call Fragments class
private BottomNavigationFragment fragmentOne;
/* private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;*/
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
setFragment(fragmentOne);
return true;
case R.id.navigation_dashboard:
/*
setFragment(fragmentTwo);
*/
return true;
case R.id.navigation_notifications:
/*
setFragment(fragmentThree);
*/
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//make new from fragments
//fragment of BottomNavigation
fragmentOne = new BottomNavigationFragment();
/* fragmentThree = new FragmentThree();
fragmentTwo = new FragmentTwo();
*/
setFragment(fragmentOne);
frameLayout = findViewById(R.id.main_fream);
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_fream, fragment);
fragmentTransaction.commit();
}
}
My Layout Of main_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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/main_fream"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
My Bottom Navigation Fragment class
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class BottomNavigationFragment extends Fragment {
TabLayout tabLayout;
EditText search;
ViewPager viewPager;
public BottomNavigationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_bottom_navigation, container, false);
search=view.findViewById(R.id.searchinfragmentOne);
tabLayout=view.findViewById(R.id.tablayout_id);
viewPager=view.findViewById(R.id.viewpager);
ViewPagerAdapterForTabs adapter = new ViewPagerAdapterForTabs(getChildFragmentManager());
// this is Tab Fragments
adapter.AddFragment(new TabFragment(),"Tab1");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
**and My Layout Of this Buttom Navigation **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".BottomNavigationFragment">
<EditText
android:id="#+id/searchinfragmentOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:hint="search ..." />
<android.support.design.widget.TabLayout
android:id="#+id/tablayout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
app:tabGravity="fill"
app:tabIndicatorColor="#color/colorPrimary"
app:tabMode="scrollable"
app:tabTextColor="#color/colorPrimaryDark" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"></android.support.v4.view.ViewPager>
</LinearLayout>
Tab Fragment
package forokans.sirwansoft.forlearn;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class TabFragment extends Fragment {
public List<Items> lstItems;
public RecyclerViewAdapter mAdapter;
EditText search;
public TabFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
lstItems = new ArrayList<>();
lstItems.add(new Items("a", "11265", "27500", "horizental", R.drawable.gemtv));
lstItems.add(new Items("b", "11265", "27500", "horizental", R.drawable.bbc));
lstItems.add(new Items("c", "11265", "27500", "horizental", R.drawable.voa));
lstItems.add(new Items("d", "11265", "27500", "horizental", R.drawable.manoto));
search = view.findViewById(R.id.searchintabbadrkurdi);
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
/*mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new RecyclerViewAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);*/
return view;
}
private void filter(String text) {
ArrayList<Items> filteredList = new ArrayList<>();
for (Items item : lstItems) {
if (item.getTvName().toLowerCase().contains(text.toLowerCase())) {
filteredList.add(item);
}
}
mAdapter.filterList(filteredList);
}
}
Tab Layout . xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TabFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/searchintabbadrkurdi"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview_id_badr_kurdi"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</FrameLayout>
My Item Class
package forokans.sirwansoft.forlearn;
public class Items {
private String TvName;
private String Forekans;
private String BistoHaft;
private String Horizental;
private int ImageSrc;
//main constructor
public Items() {
}
// constructor
public Items(String tvName, String forekans, String bistoHaft, String horizental, int imageSrc) {
TvName = tvName;
Forekans = forekans;
BistoHaft = bistoHaft;
Horizental = horizental;
ImageSrc = imageSrc;
}
//getter
public String getTvName() {
return TvName;
}
//getter
public String getForekans() {
return Forekans;
}
public String getBistoHaft() {
return BistoHaft;
}
//getter
public int getImageSrc() {
return ImageSrc;
}
public String getHorizental() {
return Horizental;
}
}
My Recycler View Adapter Class
package forokans.sirwansoft.forlearn;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<Items> lstItems;
public RecyclerViewAdapter(Context mContext, List<Items> lstItems) {
this.mContext = mContext;
this.lstItems = lstItems;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.recycler_view_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
//in main activity displays
holder.tv_Items_TvName.setText(lstItems.get(position).getTvName());
holder.tv_Items_cat.setText(lstItems.get(position).getForekans());
holder.tv_Items_desc.setText(lstItems.get(position).getBistoHaft());
holder.tv_Items_horizental.setText(lstItems.get(position).getHorizental());
holder.img_Items_ImageSrc.setImageResource(lstItems.get(position).getImageSrc());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return lstItems.size();
}
public void filterList(ArrayList<Items> filteredList) {
lstItems = filteredList;
notifyDataSetChanged();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_Items_TvName;
TextView tv_Items_cat;
TextView tv_Items_desc;
TextView tv_Items_horizental;
ImageView img_Items_ImageSrc;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
tv_Items_TvName = itemView.findViewById(R.id.Items_TvName_id);
tv_Items_cat = itemView.findViewById(R.id.Items_cat_id);
tv_Items_desc = itemView.findViewById(R.id.Items_desc_id);
tv_Items_horizental = itemView.findViewById(R.id.Items_Hor_id);
img_Items_ImageSrc = itemView.findViewById(R.id.Items_img_id);
cardView = itemView.findViewById(R.id.cardview_id);
}
}
}
And My ViewPagerAdapter class For Tabs
package forokans.sirwansoft.forlearn;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapterForTabs extends FragmentPagerAdapter {
private final List<Fragment> FragmentList = new ArrayList<>();
private final List<String> FragmentListTitles = new ArrayList<>();
public ViewPagerAdapterForTabs(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentList.get(position);
}
#Override
public int getCount() {
return FragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return FragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment, String titles) {
FragmentList.add(fragment);
FragmentListTitles.add(titles);
}
}
i found out
change this
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
to this
RecyclerView myrv = view.findViewById(R.id.recyclerview_id_badr_kurdi);
mAdapter = new RecyclerViewAdapter(getContext(), lstItems);
myrv.setLayoutManager(new GridLayoutManager(getContext(), 3));
myrv.setAdapter(mAdapter);
the reason is
before We call onCreate this RecyclerViewAdapter mAdapter = new RecyclerViewAdapter(getContext(), lstItems); was initialized and in last one if we make this class a new abject , it will be a new initializing value
I'm new with android firebase. My problem is that I would like to display the list of my data in the database in a
recycleview. I have a tablayout that contains 3 tabs. it's in the first tab that I want to display my data, I use a fragment
in which I met my recycleview, i also the method
Blockquote
addValueEventListener
Blockquote
to take my firebase data. Whenever I launch the application it displays nothing I have this message
Blockquote
E / RecyclerView: No adapter attached; skip the layout
Blockquote
.Is this someone can help me. Thanks in Advance
My Firebase Data[1]: https://imgur.com/gallery/uIOEPuA
HomeActivity.java
package com.example.saincurin.htfacile;
import android.os.Build;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabItem;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.saincurin.htfacile.Adapters.PageAdapter;
public class HomeActivity extends AppCompatActivity {
private Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
private DrawerLayout mDrawer;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.toolbar);
mDrawer = findViewById(R.id.drawer_layout);
nvDrawer = findViewById(R.id.nvView);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
// Set up Drawer View
PagerAdapter pagerAdapter = new PageAdapter(getSupportFragmentManager(), HomeActivity.this);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(HomeActivity.this,
R.color.colorAccent));
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar,
R.string.drawer_open, R.string.drawer_close);
mDrawer.addDrawerListener(toggle);
toggle.syncState();
// give the Tablayout the viewPager
tabLayout.setupWithViewPager(viewPager);
// setupDrawerContent(nvDrawer);
}
#Override
public void onBackPressed() {
if (mDrawer.isDrawerOpen(GravityCompat.START)) {
mDrawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// private void setupDrawerContent(NavigationView navigationView) {
// navigationView.setNavigationItemSelectedListener(
// new NavigationView.OnNavigationItemSelectedListener() {
// #Override
// public boolean onNavigationItemSelected(MenuItem menuItem) {
// selectDrawerItem(menuItem);
// return true;
// }
// });
// }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_products, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_more) {
Toast.makeText(this, "The more is selected", Toast.LENGTH_SHORT).show();
}else if (item.getItemId() == R.id.action_search) {
Toast.makeText(this, "The search is selected", Toast.LENGTH_SHORT ).show();
}else if (item.getItemId() == R.id.drawer_layout) {
mDrawer.openDrawer(GravityCompat.START);
}
return true;
}
}
My Model
package com.example.saincurin.htfacile.ModelData;
public class DataModel {
private String description;
private String name;
private String image;
private String price;
private String quantity;
//constructor
public DataModel() {
}
public DataModel(String name, /*String description,*/ String image, String price) {
this.name = name;
// this.description = description;
this.image = image;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
My Adapter
package com.example.saincurin.htfacile.Adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.saincurin.htfacile.ModelData.DataModel;
import com.example.saincurin.htfacile.R;
import com.squareup.picasso.Picasso;
import java.util.List;
// Create the basic adapter extending from RecyclerView.Adapter
// Note that we specify the custom ViewHolder which gives us access to our views
public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductsviewHolder> {
private Context mcontext;
// Store a member variable for the contacts
private List<DataModel> mDataModel;
public ProductsAdapter(Context context, List<DataModel> mDataModel) {
mcontext = context;
this.mDataModel = mDataModel;
}
// Usually involves inflating a layout from XML and returning the holder
#NonNull
#Override
public ProductsviewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//inflate the custom Layout
View dataView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, parent, false);
//return a new holder instance
return new ProductsviewHolder(dataView);
}
// Involves populating data into the item through holder
#Override
public void onBindViewHolder(#NonNull ProductsviewHolder holder, int position) {
// Get the data model based on position
DataModel dataModel = mDataModel.get(position);
// Set item views based on your views and data model
holder.txtName.setText(dataModel.getName());
// holder.txtDescription.setText(dataModel.getDescription());
holder.txtPrice.setText(dataModel.getPrice());
Picasso.with(mcontext)
.load(dataModel.getImage())
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public class ProductsviewHolder extends RecyclerView.ViewHolder {
public TextView txtName;
// public TextView txtDescription;
public TextView txtPrice;
public TextView txtQuantity;
public ImageView imageView;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public ProductsviewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
txtName = itemView.findViewById(R.id.rvTitleTv);
// txtDescription = itemView.findViewById(R.id.rDescriptionTv);
txtPrice = itemView.findViewById(R.id.rPrice);
imageView = itemView.findViewById(R.id.rImageView);
}
}
}
My first Fragment tab
package com.example.saincurin.htfacile.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.saincurin.htfacile.Adapters.ProductsAdapter;
import com.example.saincurin.htfacile.ModelData.DataModel;
import com.example.saincurin.htfacile.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class ProductsFragment extends Fragment {
private RecyclerView mRecycleView;
private ProductsAdapter mProductsAdapter;
private DatabaseReference mReference;
private List<DataModel> mDataModel;
View v;
public ProductsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_products, container, false);
//RecycleView
mRecycleView = v.findViewById(R.id.recycleView);
mRecycleView.setHasFixedSize(true);
//set Layout as LinearLayout
mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
mDataModel = new ArrayList<>();
//send Query FirebaseDatabase
mReference = FirebaseDatabase.getInstance().getReference("uploads");
Log.e("DEBUG", "The Reference :"+mReference);
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
DataModel dataModel = postSnapshot.getValue(DataModel.class);
mDataModel.add(dataModel);
}
// Log.e("DEBUG","The data model "+ mDataModel.toString());
mProductsAdapter = new ProductsAdapter(getContext(), mDataModel);
// Log.e("DEBUG","The data model "+ mProductsAdapter);
//set the adapter to the recyclerview
mRecycleView.setAdapter(mProductsAdapter);
mProductsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
return v;
}
}
Layout for my first tab pager
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.ProductsFragment">
<!--RecycleView-->
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Layout for my HomeActivity
<?xml version="1.0" encoding="utf-8"?>
<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"
android:fitsSystemWindows="true"
tools:context=".HomeActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/toolbar"
style="#style/myCustomTabLayout"
android:background="#color/colorPrimary"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#android:color/black">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
My item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cardBackgroundColor="#fff"
app:cardCornerRadius="3dp"
app:cardElevation="3dp"
app:cardUseCompatPadding="true"
app:contentPadding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/rvTitleTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:textColor="#000"
android:textSize="22sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/rImageView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:adjustViewBounds="true"
android:background="#drawable/loading"
android:scaleType="center" />
<TextView
android:id="#+id/rPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="150 gdes"
android:textSize="20dp"
android:textStyle="bold" />
<!--<TextView-->
<!--android:id="#+id/rDescriptionTv"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:text="This is the post description that"-->
<!--android:textSize="20sp" />-->
</LinearLayout>
</android.support.v7.widget.CardView>
Welcome to StackOverflow. The RecyclerView is quite specific when it comes to its setup. So you need to make sure you set up the adapter before setting the layout manager and the fixedSize property.
Try changing your onCreateView method to this:
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_products, container, false);
// Notice that I changed the order of RecyclerView setup
mRecycleView = v.findViewById(R.id.recycleView);
mDataModel = new ArrayList<>();
mProductsAdapter = new ProductsAdapter(getContext(), mDataModel);
mRecyclerView.setAdapter(mProductsAdapter);
mRecycleView.setHasFixedSize(true);
//set Layout as LinearLayout
mRecycleView.setLayoutManager(new LinearLayoutManager(getContext()));
//send Query FirebaseDatabase
mReference = FirebaseDatabase.getInstance().getReference("uploads");
mReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
DataModel dataModel = postSnapshot.getValue(DataModel.class);
mDataModel.add(dataModel);
}
mProductsAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
return v;
}
I have been searching a lot of tutorials to implement an on item long press Listener on a Listview which is Inside a RecyclerView. So far I had no luck.
I want a menu to more ap after holding the List Item for some time. I am attaching my code here please help me with it.
I have added my complete code Including the MainAcyivity.
I have a tabbed view which contains 3tabs. Inside the tab view, there is a fragment which contains a Listview.
I want the List to be long pressed to bring a popup menu which has as add or delete options.
MainActivity.java
package tabbardemo.com.materialdesigntabs_demo;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static Toolbar toolbar;
private static ViewPager viewPager;
private static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager
//Implementing tab selected listener over tablayout
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.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) {
}
});
}
//Setting View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment("Inbox"), "Inbox");
adapter.addFrag(new EventsFragment("QA"), "QA");
adapter.addFrag(new EventsFragment("Events"), "Events");
viewPager.setAdapter(adapter);
}
//View Pager fragments setting adapter class
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();//fragment arraylist
private final List<String> mFragmentTitleList = new ArrayList<>();//title arraylist
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
//adding fragments and title method
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinatorLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- AppBar Layout -->
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="fill_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<!-- Tab Layout for creating tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<!-- Helps handing the Fragments for each Tab -->
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
dummy_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/blue"
android:gravity="center"
android:orientation="vertical">
<!-- Recycler View -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
</LinearLayout>
DummyFragment.java
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 16/09/15.
*/
public class DummyFragment extends Fragment {
private View view;
private String title;//String for tab title
private static RecyclerView recyclerView;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
public DummyFragment(String title) {
this.title = title;//Setting tab title
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.dummy_fragment, container, false);
setRecyclerView();
return view;
}
//Setting recycler view
private void setRecyclerView() {
recyclerView = (RecyclerView) view
.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView
.setLayoutManager(new LinearLayoutManager(getActivity()));//Linear Items
ArrayList<String> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
arrayList.add(title+" Items " + i);//Adding items to recycler view
}
RecyclerView_Adapter adapter = new RecyclerView_Adapter(getActivity(), arrayList);
recyclerView.setAdapter(adapter);// set adapter on recyclerview
}
}
RecyclerView_Adapter
package tabbardemo.com.materialdesigntabs_demo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
/**
* Created by SONU on 10/09/15.
*/
public class RecyclerView_Adapter extends
RecyclerView.Adapter<DemoViewHolder> {
private ArrayList<String> arrayList;
private Context context;
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public RecyclerView_Adapter(Context context,
ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
#Override
public void onBindViewHolder(DemoViewHolder holder,
int position) {
final DemoViewHolder mainHolder = (DemoViewHolder) holder;
//Setting text over textview
// mainHolder.bind(arrayList.get(position), listener);
mainHolder.title.setText(arrayList.get(position));
}
#Override
public DemoViewHolder onCreateViewHolder(
ViewGroup viewGroup, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext());
ViewGroup mainGroup = (ViewGroup) mInflater.inflate(
R.layout.item_row, viewGroup, false);
DemoViewHolder mainHolder = new DemoViewHolder(mainGroup) {
#Override
public String toString() {
return super.toString();
}
};
// 13805 ////////////////////////////////
return mainHolder;
}
}
DemoViewHolder.java
package tabbardemo.com.materialdesigntabs_demo;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by SONU on 31/08/15.
*/
public abstract class DemoViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public DemoViewHolder(View view) {
super(view);
this.title = (TextView) view.findViewById(R.id.cardTitle);
}
}
ite_row.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/iv_image"
android:padding="10dp"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:src="#mipmap/ic_launcher">
</ImageView>
<TextView
android:id="#+id/cardTitle"
android:layout_toRightOf ="#+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:padding="15dp"
android:text="Card Title"
android:textColor="#000000"
android:textSize="17sp" ></TextView>
</RelativeLayout>
1- create your menu items (your list item to show on long click)
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/one"
android:title="One"/>
<item
android:id="#+id/two"
android:title="Two"/>
<item
android:id="#+id/three"
android:title="Three"/>
</menu>
2- setup listener and menu.
#Override
public void onBindViewHolder(DemoViewHolder holder, int position) {
holder.title.setText(arrayList.get(position));
holder.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showMenu(v);
return true;
}
});
}
// method to open a popup menu(list) upon long click in the recyclerView item
private void showMenu(View view){
PopupMenu popup = new PopupMenu(context,view );
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
popup.show();
}
When you are doing setOnItemLongClickListener() in the ListView:
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// Dialog/Popup will appears here
showAddDeleteDialog();
return true;
}
});
public void showAddDeleteDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setCancelable(false);
dialog.setTitle("Add or Delete Dialog");
// dialog.setMessage("Are you sure you want to delete this entry?" );
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Action for "Add".
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action for "Delete".
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
I want to use list view by using custom list view adapter. My problem is that I am not getting list view at run time in my app.
CourseActivity.java
package com.technerdshub.vusocial.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.technerdshub.vusocial.DBHelper;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.Models.User;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
public class CourseActivity extends AppCompatActivity {
ListView list;
ArrayList arrayList = new ArrayList();
CourseViewAdapter adapter;
Course courseObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_activity);
List<Course> courseList;
DBHelper db = new DBHelper(this);
courseList = db.getAllCourses();
list = (ListView) findViewById(R.id.listview1);
for (Course c : courseList)
{
arrayList.add(c);
}
adapter = new CourseViewAdapter(this, arrayList);
adapter.courseActivity = this;
list.setAdapter(adapter);
User user = User.getInstance();
saveUserOnParse(user);
}
private void saveUserOnParse(User user) {
ParseObject parseUser = new ParseObject("UserData");
parseUser.put("name", user.getName());
parseUser.put("vuId", user.getVuId());
parseUser.put("studyProgram", user.getStudyProgram());
parseUser.put("facebookId", user.getFacebookId());
parseUser.put("facebookEmail", user.getFacebookEmail());
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e==null){
// Intent i = new Intent(getContext(), StudentDashboardActivity.class);
//// i.putExtra("E-mail", "abc");
// startActivity(i);
}
else {
Toast temp = Toast.makeText(CourseActivity.this,"Data is not saved.", Toast.LENGTH_SHORT);
temp.show();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 4
if(requestCode==2)
{
courseObject = (Course) data.getExtras().getSerializable("SelectedCourse");
}
}
}
CourseViewAdapter.java
package com.technerdshub.vusocial.Activities;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Saroosh on 7/16/2016.
*/
public class CourseViewAdapter extends BaseAdapter {
protected CourseActivity courseActivity;
Context mContext;
LayoutInflater inflater;
private List<Course>worldpopulationlist=null;
private ArrayList<Course> arraylist;
public CourseViewAdapter(Context context, List<Course>worldpopulationlist){
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Course>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView courseCode;
TextView courseName;
}
#Override
public int getCount() {
return 0;
}
#Override
public Course getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.c_list_item, null);
// Locate the TextViews in listview_item.xml
holder.courseName = (TextView) view.findViewById(R.id.course_name);
holder.courseCode = (TextView) view.findViewById(R.id.course_code);
// holder.duration = (TextView) view.findViewById(R.id.program_duration);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.courseName.setText(worldpopulationlist.get(position).getCourseName());
holder.courseCode.setText(worldpopulationlist.get(position).getCourseCode());
//holder.duration.setText(worldpopulationlist.get(position).getDuration());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, CourseActivity.class);
// Pass all data ran
intent.putExtra("SelectedCourse", worldpopulationlist.get(position));
// Pass all data country
courseActivity.setResult(2,intent);
courseActivity.finish();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (Course wp : arraylist)
{
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
course_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.CourseActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<include
android:id="#+id/my_tool_bar"
layout="#layout/tool_bar"
>
</include>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_c" />
</android.support.design.widget.CoordinatorLayout>
c_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="4dp"
android:paddingRight="4dp"
>
<TextView
android:id="#+id/course_code"
android:layout_width="70dp"
android:layout_height="70dp"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/course_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/course_code"
android:paddingBottom="5dp"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</RelativeLayout>
First of all your getCount() returns 0 which means you are telling the Adapter that there's nothing in there, try returning arraylist.size()
Moreover, why are there two lists in your Adapter?
Edit : Nevermind, it's for your filtering I see, then try returning worldpopulationlist.size()
You can use this code for it as you need to return size in adapter getCount method:
#Override
public int getCount() {
return arraylist.size();
}
#Override
public Course getItem(int position) {
return arraylist.get(position);
}
Get your worldpopulationlist array count
public int getCount() {
return worldpopulationlist.size();
}
Remove these methods
#Override
public int getCount() {
return 0;
}
#Override
public Course getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change your class definition
public class CourseViewAdapter extends ArrayAdapter<Course>
Use only one list (there's an alternative, correct way, to apply filters to an Adapter)
Context mContext;
LayoutInflater inflater;
private List<Course> arraylist;
public CourseViewAdapter(Context context, ArrayList<Course> list){
super(context, 0, list);
mContext = context;
inflater = LayoutInflater.from(context);
this.arraylist = list;
}
Your problem was that the getCount method tells the UI how many elements to draw. You must implement that in a BaseAdapter, but an ArrayAdapter does that for you
in your xmlcourse_activity.xml you have to initialize ListView
<ListView
android:id="#+id/listview1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
In listView you have to inflate your c_list_item.xml layout.
I hope it will work for you.
my app has custom ListView, each row contains checkbox ,edit text and 2 buttons. In the main xml layout file i have 1 submit button and listView. i want that, when i click on submit button, i should get all checked row position.I am new to android programming ,so plz help me my code is not working here is my code:
main.xml
<?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">
<Button android:layout_height="wrap_content"
android:text="#string/button_submit"
android:layout_width="wrap_content"
android:id="#+id/main_submit_button" android:onClick="#string/button_submit"></Button>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
items.xml
<?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="wrap_content">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_weight="1"
android:id="#+id/items_name"
android:gravity="left"
android:textStyle="bold" />
<CheckBox android:id="#+id/items_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="#+id/items_add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/text_switcher_plus" />
<EditText android:digits="10"
android:textStyle="bold" android:gravity="left"
android:id="#+id/items_plates" android:layout_height="wrap_content"
android:layout_width="90dp"></EditText>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/items_minus_button"
android:text="#string/text_switcher_minus"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
VegmenuActivity
package com.sagar.resmenu;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
// reference:http://pareshnmayani.wordpress.com/tag/android-custom-listview-example
public class VegmenuActivity extends Activity implements OnItemClickListener{
//dynamic array that contains names of items
private ArrayList<String> items = new ArrayList<String>
(Arrays.asList("Veg pulav", "Pav bhaji", "Panir tikka", "veg kolhapuri",
"Coconut Rice", "Curd rice", "Mint Pulao",
"Banana Custard","Basundi", "Cheese potato Tikkis",
"Dum aloo"));
private ArrayList<Integer> counter = new ArrayList<Integer>
(Arrays.asList(0, 0,0, 0, 0,0, 0,0, 0,0,0));
private SparseBooleanArray a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView lv =(ListView)findViewById(R.id.list_view);
// lv.setOnClickListener(null);
MyAdapter adapter = new MyAdapter(getApplicationContext(),items,counter);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button submit1;
submit1 = (Button)findViewById(R.id.main_submit_button);
submit1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = lv.getCheckedItemPositions();
int len = items.size();
for (int i = 0; i < len; i++)
{
if(a.valueAt(i) == true)
Log.d("Returned ", String.valueOf(a.valueAt(i)));
}
}
});
}
//private OnItemClickListener selectCat = new OnItemClickListener();
public void onItemClick(AdapterView<?> a, View v, int positon, long id) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
package com.sagar.resmenu;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextSwitcher;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter implements OnClickListener{
private LayoutInflater inflater;
private ArrayList<String> data;
VegmenuActivity m;
private ArrayList<Integer> counter;
public MyAdapter(Context context, ArrayList<String> data,ArrayList<Integer> counter) {
// TODO Auto-generated constructor stub
super();
// Caches the LayoutInflater for quicker use
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Sets the events data
this.data= data;
this.counter=counter;
}
public int getCount() {
return this.data.size();
//return this.counter.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return null;
}
public long getItemId(int position) throws IndexOutOfBoundsException{
return 0;
}
public int getViewTypeCount(){
return 1;
}
public static class ViewHolder
{
TextView items_name;
CheckBox items_check ;
Button items_plus_button;
Button items_minus_button;
EditText plates;
}
public View getView(int position, View convertView, ViewGroup parent){
//String myText = getItem(position);
ViewHolder holder;
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.items,parent,false);
holder.items_name = (TextView) convertView.findViewById(R.id.items_name);
holder.plates = (EditText) convertView.findViewById(R.id.items_plates);
holder.items_check = (CheckBox) convertView.findViewById(R.id.items_check);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.items_name.setText(data.get(position));
holder.plates.setText(String.valueOf(counter.get(position)));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
when I need check boxes inside listview, I often code as following:
MyAdapter.java:
- Declare an boolean array to mark which item is checked/unchecked:
....
boolean[] checked;
...
inside constructor:
checked = new boolean[data.size()];
- Inside getView()
{
.....
holder.items_check.setChecked(checked[position]);
holder.items_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked[position] = isChecked;
}
});
.....
- And method to get all checked items:
boolean[] getCheckedItems() {
return checked;
}
That's !
Could it be that your getItem and getItemId only return null and 1? These methods need to return the correct data for this to work I believe. getItem would need to be:
String getItem(int position)
{
return data.get(position);
}
and getItemId would simply return position instead of 0:
String getItemId(int position)
{
return position;
}