I am trying to implement a toggle button into the Navigation Drawer Project, that Android Studio can automatically generate.
In the end I want to have something like this ("Downloaded only"-Button):
Unfortunately I don't understand how to add a toggle button to the ListView of the NavDrawer. I could probably use one of the "Custom NavDrawer Libs" out there but I would like to understand the way Google proposes it with the auto generated example.
Any ideas on how to implement this into the default NavDrawer Project?
I would do something like this: instead of using a listview I would use an RecyclerView.
Then I create three different layout definitions for the label with icon, the divider and the label with optional switch. Your RecyclerView Adapter should extend Form RecyclerView.Adapter. For each of those three layouts you should create an own implementation of ViewHolder. Now you have to create several classes for the list items and one superclass for all of them. In your Adapter you have to override the getViewType method.
Tomorrow when I'm at work I could post some demo code for you.
Edit:
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"
tools:context="de.devhew.navigationdrawerexample.MainActivity">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/AppTheme.Toolbar.Overflow"
app:theme="#style/AppTheme.Toolbar" />
<FrameLayout
android:id="#+id/main_content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="de.devhew.navigationdrawerexample.drawer.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<NavDrawerEntry> drawerEntries = new ArrayList<>();
drawerEntries.add(new NavDrawerItemWithIcon("Home", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("People", R.drawable.app_generic));
drawerEntries.add(new NavDrawerItemWithIcon("Stuff", R.drawable.app_generic));
drawerEntries.add(new NavDrawerDivider());
drawerEntries.add(new NavDrawerItem("Settings"));
drawerEntries.add(new NavDrawerToggle("Wifi only"));
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.init((android.support.v4.widget.DrawerLayout) findViewById(R.id.drawer_layout),
toolbar, drawerEntries);
}}
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private View root;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
return root;
}
public void init(DrawerLayout drawerLayout, final Toolbar toolbar, List<NavDrawerEntry> drawerEntries) {
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();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mRecyclerView = (RecyclerView) root.findViewById(R.id.nav_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.setHasFixedSize(true);
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(getActivity(), drawerEntries);
mRecyclerView.setAdapter(adapter);
}}
NavigationDrawerAdapter.java
public class NavigationDrawerAdapter
extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<NavDrawerEntry> data;
private LayoutInflater inflater;
public NavigationDrawerAdapter(Context context, List<NavDrawerEntry> data) {
this.data = data;
this.inflater = LayoutInflater.from(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemLayoutView;
switch (viewType) {
case 0:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item_with_icon, viewGroup, false);
ItemWithIconVH holder = new ItemWithIconVH(itemLayoutView);
return holder;
case 1:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_divider, viewGroup, false);
DividerVH dividerViewHolder = new DividerVH(itemLayoutView);
return dividerViewHolder;
case 2:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_item, viewGroup, false);
ItemVH itemViewHolder = new ItemVH(itemLayoutView);
return itemViewHolder;
case 3:
itemLayoutView = inflater.inflate(R.layout.layout_nav_drawer_toggle, viewGroup, false);
ToggleVH toggleViewHolder = new ToggleVH(itemLayoutView);
return toggleViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final NavDrawerEntry item = data.get(position);
if (item instanceof NavDrawerItemWithIcon) {
ItemWithIconVH viewHolder = (ItemWithIconVH) holder;
viewHolder.mTitle.setText(((NavDrawerItemWithIcon) item).getTitle());
viewHolder.mImageView.setImageResource(((NavDrawerItemWithIcon) item).getIconId());
}
if (item instanceof NavDrawerItem) {
ItemVH viewHolder = (ItemVH) holder;
viewHolder.mTitle.setText(((NavDrawerItem) item).getTitle());
}
if (item instanceof NavDrawerToggle) {
ToggleVH viewHolder = (ToggleVH) holder;
viewHolder.mTitle.setText(((NavDrawerToggle) item).getTitle());
viewHolder.mSwitch.setChecked(((NavDrawerToggle) item).isChecked());
}
}
#Override
public int getItemViewType(int position) {
if (data.get(position) instanceof NavDrawerItemWithIcon)
return 0;
if (data.get(position) instanceof NavDrawerDivider)
return 1;
if (data.get(position) instanceof NavDrawerItem)
return 2;
if (data.get(position) instanceof NavDrawerToggle)
return 3;
return -1;
}
#Override
public int getItemCount() {
return data.size();
}
class ItemWithIconVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final ImageView mImageView;
public ItemWithIconVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mImageView = (ImageView) itemView.findViewById(R.id.nav_item_image);
}
}
class DividerVH extends RecyclerView.ViewHolder {
public DividerVH(View itemView) {
super(itemView);
}
}
class ItemVH extends RecyclerView.ViewHolder {
final TextView mTitle;
public ItemVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
}
}
class ToggleVH extends RecyclerView.ViewHolder {
final TextView mTitle;
final Switch mSwitch;
public ToggleVH(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nav_item_title);
mSwitch = (Switch) itemView.findViewById(R.id.nav_switch);
}
}}
Superclass for all NavDrawer Items:
public class NavDrawerEntry {}
Item without icon:
public class NavDrawerItem extends NavDrawerEntry {
private String title;
public NavDrawerItem(String title) {
this.setTitle(title);
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Item with icon:
public class NavDrawerItemWithIcon extends NavDrawerEntry {
private String title;
private int iconId;
public NavDrawerItemWithIcon(String title, int iconId) {
this.setTitle(title);
this.setIconId(iconId);
}
public int getIconId() {
return iconId;
}
private void setIconId(int iconId) {
this.iconId = iconId;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
Divider:
public class NavDrawerDivider extends NavDrawerEntry {}
Item with Switch:
public class NavDrawerToggle extends NavDrawerEntry {
private String title;
private boolean checked;
public NavDrawerToggle(String title) {
this.setTitle(title);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String getTitle() {
return title;
}
private void setTitle(String title) {
this.title = title;
}}
layout_nav_drawer_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_item_with_icon.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_item_image"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:src="#drawable/app_generic" />
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" /></LinearLayout>
layout_nav_drawer_divider.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#ddd"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp" /></LinearLayout>
layout_nav_drawer_toggle.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true">
<TextView
android:id="#+id/nav_item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:fontFamily="sans-serif"
android:text="Verbundene Geräte"
android:textColor="#000"
android:textSize="16sp" />
<Switch
android:id="#+id/nav_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp" /></RelativeLayout>
fragment_navigation_drawer.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="280dp"
android:layout_height="match_parent"
android:background="#eee"
tools:context="de.vacom.hew.materialdemo.NavigationDrawerFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:background="#color/primaryColor"
android:elevation="3dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/nav_app_icon"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="55dp"
android:src="#drawable/app_generic" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="64dp"
android:fontFamily="sans-serif-medium"
android:text="Demo App"
android:textColor="#eee"
android:textSize="18sp" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/nav_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout></FrameLayout>
Related
The problem is each and every time when I send the edittext field from pressing save button I think the items are being overlapped or it may be every time i add the values from edit text field old one may be replaced by new values.They are not appearing in the list.
This is the class from where i send the edit text fields
public class MyEditor extends AppCompatActivity {
EditText textIn,txtHeading;
Button buttonAdd,btnsave;
ArrayList<String> nameList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editor);
txtHeading = (EditText)findViewById(R.id.heading);
buttonAdd = (Button)findViewById(R.id.add);
btnsave =(Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newName = txtHeading.getText().toString();
Intent intent = new Intent(getApplicationContext(),BuilderPage.class);
intent.putStringArrayListExtra("key", nameList);
nameList.add(newName);
int listsize = nameList.size();
for (int i=0;i<listsize;i++){
Log.i("Lists are", nameList.get(i)) ;
}
startActivity(intent);
Toast.makeText(MyEditor
.this,"You added" +newName.toUpperCase()+ "in your view",Toast.LENGTH_LONG).show();
}
});
}
}
This is my Layout that contains RecyclerView.
<?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"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_builderxml"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:animateLayoutChanges="false"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_builderxml"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways" >
<EditText
android:layout_width="350dp"
android:id="#+id/edittxtsurvey"
android:layout_height="wrap_content"
android:hint="Enter Your SurveyName"/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<RelativeLayout android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="bottom" >
<SlidingDrawer android:layout_width="wrap_content"
android:id="#+id/SlidingDrawer"
android:handle="#+id/slideHandleButton"
android:content="#+id/contentLayout"
android:padding="10dip"
android:layout_height="120dip">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/slideHandleButton"
android:src="#drawable/arrowdown">
</ImageView>
<RelativeLayout
android:layout_width="wrap_content"
android:background="#1a237e"
android:id="#+id/contentLayout"
android:gravity="center|top"
android:padding="10dip"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/plaintext"
android:id="#+id/imgviewplaintext"
android:padding="5dp"
android:onClick="oOnClick_PlainText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/checkbox"
android:id="#+id/imgviewcheckbox"
android:onClick="OnClick_CheckBox"
android:padding="5dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgviewradiobutton"
android:layout_toStartOf="#+id/imgviewradiobutton"
android:layout_marginRight="21dp"
android:layout_marginEnd="21dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/radio"
android:id="#+id/imgviewradiobutton"
android:padding="5dp"
android:onClick="OnClick_RadioButton"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgviewtextbox"
android:layout_toStartOf="#+id/imgviewtextbox"
android:layout_marginRight="37dp"
android:layout_marginEnd="37dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/textbox"
android:id="#+id/imgviewtextbox"
android:onClick="onClick_textbox"
android:padding="5dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="30dp"
android:layout_marginEnd="30dp" />
</RelativeLayout>
</SlidingDrawer>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
This is my Builder class that contains Builder xml.
public class BuilderPage extends ActionBarActivity implements RecyclerViewAdapter.OnItemClickListener {
private RecyclerView myRecyclerView;
private LinearLayoutManager linearLayoutManager;
private RecyclerViewAdapter myRecyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.builder_layout);
ButterKnife.bind(this);
setSupportActionBar(toolbar1);
getSupportActionBar().setDisplayShowTitleEnabled(false);
dbHelper = new DbHelper(this);
dbHelper.getWritableDatabase();
ArrayList<String> nameList = getIntent().getStringArrayListExtra("key");
myRecyclerView = (RecyclerView)findViewById(R.id.recyclerView_builderxml);
linearLayoutManager =
new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL,false);
myRecyclerViewAdapter = new RecyclerViewAdapter(this,nameList);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
myRecyclerViewAdapter.setOnItemClickListener(this);
This my Adapter class
public class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ItemHolder> {
private List<String> itemsName;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
public RecyclerViewAdapter(Context context,ArrayList<String> nameList){
layoutInflater = LayoutInflater.from(context);
itemsName = nameList;
}
#Override
public RecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.text_view,parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
}
#Override
public int getItemCount() {
return (null != itemsName ? itemsName.size() : 0);
}
public void setOnItemClickListener(OnItemClickListener listener){
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener(){
return onItemClickListener;
}
public interface OnItemClickListener{
public void onItemClick(ItemHolder item, int position);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private RecyclerViewAdapter parent;
TextView textItemName;
public ItemHolder(View itemView, RecyclerViewAdapter parent) {
super(itemView);
itemView.setOnClickListener(this);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.herecomes);
}
public void setItemName(CharSequence name){
textItemName.setText(name);
}
public CharSequence getItemName(){
return textItemName.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if(listener != null){
listener.onItemClick(this, getPosition());
}
}
}}
You are using same textitemname everytime.change
#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
}
to
#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemHolder holder, int position) {
holder.textItemName.setText(itemsName.get(position));
}
The recycler view is showing other details in activity, except the image. I am loading an image through AsyncTask in getImage(). What am I doing wrong?
Here's my code:
MainActivity.java
int i;
Bitmap bitmap,imageOfPoday;
RecyclerView rvPoday;
ProductAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
pd = ProgressDialog.show(MainActivity.this, "Please Wait...", null, true, true);
callPoday(PODAY_URL);
}
public List<Product> getDataPoday() {
List<Product> data=new ArrayList<>();
for(i = 0; i < parsedPODAY_ID.size(); i++) {
Product current=new Product();
current.productName=parsedPODAY_NAME.get(i);
current.price=parsedPODAY_OFFPRICE.get(i);
current.pImage=getImage("http://www.tontosworld.com/img/productimages/" + parsedPODAY_P_IMG.get(i));
Toast.makeText(this,current.pImage+"",Toast.LENGTH_LONG).show();
data.add(current);
}
return data;
}
public Bitmap getImage(String s) {
LoadImageTask task=new LoadImageTask();
task.execute(s);
return imageOfPoday;
}
class LoadImageTask extends AsyncTask<String,String,Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(strings[0]).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap b) {
super.onPostExecute(b);
if(b == null) {
Toast.makeText(MainActivity.this,"Error in loading image",Toast.LENGTH_LONG).show();
}
else {
imageOfPoday=b;
Toast.makeText(MainActivity.this,"This is for image"+imageOfPoday,Toast.LENGTH_LONG).show();
}
}
}
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.MyViewHolder> {
public LayoutInflater inflater;
List<Product> data= Collections.emptyList();
public ProductAdapter(Context context,List<Product> data){
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.recycler_view_single,parent,false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Product current = data.get(position);
holder.name.setText(current.productName);
holder.price.setText(current.price);
holder.image.setImageBitmap(current.pImage);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,price;
ImageView image;
public MyViewHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.rvItemName);
price = (TextView)itemView.findViewById(R.id.rvItemPrice);
image = (ImageView)itemView.findViewById(R.id.rvItemImage);
}
}
}
Product.java
public class Product {
String productName, price;
Bitmap pImage;
}
recycler_view_single.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="?android:selectableItemBackground">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/rvItemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/rvItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<TextView
android:id="#+id/rvItemPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product of the day"
android:textSize="25sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textColor="#000"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rvProductOfTheDay">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
android:name="com.tontosworld.tontosworld.NavigationDrawerFragment">
</fragment>
</android.support.v4.widget.DrawerLayout>
Thanks for your help.
You are missing the update notice for your adapter (which displays the data).
Everytime you update your List, you need to call
adapter.notifyDataSetChanged();
//if you only change one item, and use recyclerview, call:
adapter.notifyItemChanged();
I am making an app which consists of a navigation drawer and a recycler view inside it. However, the items inside the recycler view are not being displayed. I am not sure what I have been doing wrong. I will provide what I have. If you require anything please ask. Thanks
Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data = Collections.emptyList();
public Adapter(Context context, List<Information> data){
inflater=LayoutInflater.from(context);
this.data=data;
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder= new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder viewHolder, int i) {
Information current = data.get(i);
viewHolder.title.setText(current.title);
viewHolder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
Information
public class Information {
int iconId;
String title;
}
NavigationDrawerFragment
public class NavigationDrawerFragment extends Fragment {
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private boolean mUserLearnedDrawer;
private View containerView;
private Adapter adapter;
private boolean mFromSavedInstanceState;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer= Boolean.valueOf(readFrompreferences(getActivity(),KEY_USER_LEARNED_DRAWER,"false"));
if(savedInstanceState!=null)
{
mFromSavedInstanceState=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView=(RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new Adapter(getActivity(),getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int[] icons={R.drawable.thechefhat,R.drawable.thegrocerybasket,R.drawable.favouritesstar,R.drawable.supported};
String[] titles = {"Recipes","Ingredients","Favourites","Help"};
for(int i=0;i<titles.length&&i<icons.length;i++){
Information current = new Information();
current.iconId=icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
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);
if(!mUserLearnedDrawer){
mUserLearnedDrawer=true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER,mUserLearnedDrawer+"");
}
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);
if(slideOffset<0.6)
toolbar.setAlpha(1-slideOffset);
}
};
if(!mUserLearnedDrawer&&!mFromSavedInstanceState){
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context,String preferenceName, String preferenceValue){
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(preferenceName,preferenceValue);
editor.apply();
}
public static String readFrompreferences(Context context, String preferenceName, String defaultValue){
SharedPreferences sharedPreferences=context.getSharedPreferences(PREF_FILE_NAME,Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName,defaultValue);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar)findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer,(DrawerLayout)findViewById(R.id.drawer_Layout), toolbar);
}
#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 Home/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);
}
}
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:padding="8dp"
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/supported"
/>
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Text"
android:padding="8dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/lightPrimaryColor"
tools:context="com.example.ivan.tutorialapp.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="280dp"
android:layout_height="140dp"
android:layout_marginBottom="16dp"
android:src="#drawable/banner" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:padding="8dp"
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="#drawable/supported"
/>
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy Text"
android:padding="8dp"
android:layout_gravity="center_vertical" />
</LinearLayout>
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:fitsSystemWindows="true"
android:layout_height="match_parent">
<RelativeLayout
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ivan.tutorialapp.MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar">
</include>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/app_bar"
android:text="#string/hello_world"
/>
</RelativeLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.example.ivan.tutorialapp.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer">
</fragment>
</android.support.v4.widget.DrawerLayout>
You should change this method to return actual item count
#Override
public int getItemCount() {
return 0;
}
I have a list View in my drawer layout that I want to setlistener for each item, I read a couple of post and setFocusable, setclickiable, setfocusableInTouchMode to false for each element of listView but still doesn't work. Thank you in advanced. Here is My code :
targetItem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#ffffff"
android:focusable="true"
android:clickable="true"
>
<!-- icon -->
<ImageView
android:id="#+id/item_icon"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="8dp"
android:layout_marginRight="18dp"
android:layout_marginTop="25dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
<!-- title -->
<TextView
android:id="#+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/item_icon"
android:textSize="12dp"
android:layout_marginTop="28dp"
android:layout_marginRight="15dp"
android:textColor="#000000"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
<TextView
android:id="#+id/item_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/item_icon"
android:textSize="12dp"
android:layout_marginTop="28dp"
android:layout_marginRight="15dp"
android:textColor="#000000"
android:visibility="gone"
android:clickable="false"
android:focusableInTouchMode="false"
android:focusable="false"/>
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".MainActivity" >
<!-- The navigation drawer -->
<ListView
android:id="#+id/listview"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="end"
android:background="#ffffff"
android:choiceMode="singleChoice"
android:clickable="true"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:focusable="true"
android:focusableInTouchMode="true" />
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
.
.
.
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sidebar();
}
private void sidebar() {
MyAdapter adapter = new MyAdapter(this, generateData());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.listview);
mDrawerList.setAdapter(adapter);
mDrawerList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet,
android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(), "Hello",
Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<Model> generateData() {
ArrayList<Model> models = new ArrayList<Model>();
models.add(new Model("TimiT "));
models.add(new Model(R.drawable.home,home,1));
models.add(new Model(R.drawable.basket, basket,2));
models.add(new Model(R.drawable.list, list,3));
return models;
}
MyAdapter.java
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.target_item, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView( final int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.target_item, parent, false);
rowView.setFocusable(true);
rowView.setClickable(true);
rowView.setFocusableInTouchMode(true);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView idView = (TextView) rowView.findViewById(R.id.item_id);
imgView.setImageResource(modelsArrayList.get(position).getIcon());
imgView.setFocusable(false);
imgView.setClickable(false);
imgView.setFocusableInTouchMode(false);
titleView.setText(modelsArrayList.get(position).getTitle());
titleView.setFocusable(false);
titleView.setFocusableInTouchMode(false);
titleView.setClickable(false);
idView.setText(modelsArrayList.get(position).getID());
idView.setFocusable(false);
idView.setFocusableInTouchMode(false);
idView.setClickable(false);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Hello", Toast.LENGTH_LONG).show();
}
});
}
else{
rowView = inflater.inflate(R.layout.group_header_item, parent, false);
TextView titleView = (TextView) rowView.findViewById(R.id.header);
titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Model.java
public class Model {
private int icon;
private String title;
private int id;
private boolean isGroupHeader = false;
public Model(String title) {
this(-1,title,0);
isGroupHeader = true;
}
public Model(int icon, String title,int id) {
super();
this.icon = icon;
this.title = title;
this.id = id;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getID() {
return icon;
}
public void setID(int id) {
this.id = id;
}
public boolean isGroupHeader() {
return isGroupHeader;
}
public void setGroupHeader(boolean isGroupHeader) {
this.isGroupHeader = isGroupHeader;
}
}
the problem is this line rowView.setOnClickListener. Registering the onClickListener is preventing the onItemClik to be fired. Get rid of it, and it will work. If you want to handla an additional click listener on your list item, you have to set the OnClickListener on a child of the convertView, not on the convertView itself and add android:descendantFocusability="blocksDescendants" to the root of your list item xml
I want to make a ListView inside a RecyclerView that should display some data in a list form. I currently have a basic Adapter and RecyclerView with no ListView inside of it, so can someone tell me how to modify my code to include a listview inside the RecyclerView?
Adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.AdapterViewHolder> {
public static class AdapterViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView summary;
AdapterViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.recycler_list_title);
summary = (TextView) itemView.findViewById(R.id.recycler_list_summary);
}
}
List<Items> items;
public RVAdapter(List<Items> items){
this.items = items;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_recycler, viewGroup, false);
AdapterViewHolder pvh = new AdapterViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(AdapterViewHolder adapterViewHolder, int i) {
adapterViewHolder.title.setText(item.get(i).title);
adapterViewHolder.summary.setText(item.get(i).summary);
}
#Override
public int getItemCount() {
return item.size();
}
}
Items:
public class Items {
String title;
String summary;
public Items(String title, String summary) {
this.title = title;
this.summary = summary;
}
}
Layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="0dp" />
</LinearLayout>
list_recycler:
<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:paddingRight="?android:attr/scrollbarSize">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="6dp"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp">
<TextView
android:id="#+id/recycler_list_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColor"
android:textSize="16sp"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/recycler_list_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColorSub"
android:textSize="14sp"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
How I'm creating the ListView:
private List item;
private RecyclerView rv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
rv = (RecyclerView) ((Activity) MainActivity.context).findViewById(R.id.recycler);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this));
initializeData();
initializeAdapter();
}
private void initializeData(){
item = new ArrayList<>();
item.add(new Items("Title", "Summary"));
}
private void initializeAdapter() {
RVAdapter adapter = new RVAdapter(item);
rv.setAdapter(adapter);
}
}
ListView listview = (ListView) findViewById(R.id.listview);
ListView parentListView=(ListView)listview.getParent();
you can get parent listView by this way