I am fairly new to Android and java. I am trying to make an application with multiple pages that you can swipe through. I started from a ViewPager2 example that is using a RecyclerView. It has 2 layout files. A main one and a viewPager one that is used for all the different pages, but with a different background color and title.
I have added a switch button on the viewpager xml and want to synchronize this button so it has the same state on all pages. But it does not do that out of the box. It seems the switch is created again for each of the different pages and I don't know how to access them on the other pages when the button on the current page is being changed.
It seems like a very simple thing to do, but I cannot find how to do it. Below is the code for my 2 java files.
Any help would be greatly appreciated.
public class MainActivity extends AppCompatActivity {
ViewPager2 viewPager2;
boolean continuous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewPager2);
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected (int position) {
if (continuous == true) continuous = false;
else continuous = true;
int pos = position;
}
});
List<String> list = new ArrayList<>();
list.add("First Screen");
list.add("Second Screen");
list.add("Third Screen");
list.add("Fourth Screen");
viewPager2.setAdapter(new ViewPagerAdapter(this, list, viewPager2));
}
}
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ViewPager2 viewPager2;
private int[] colorArray = new int[]{android.R.color.black, android.R.color.holo_blue_dark, android.R.color.holo_green_dark, android.R.color.holo_red_dark};
ViewPagerAdapter(Context context, List<String> data, ViewPager2 viewPager2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.viewPager2 = viewPager2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.item_viewpager, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
holder.relativeLayout.setBackgroundResource(colorArray[position]);
}
#Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView myTextView;
RelativeLayout relativeLayout;
Button button;
Switch switch2;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.tvTitle);
relativeLayout = itemView.findViewById(R.id.container);
button = itemView.findViewById(R.id.btnToggle);
switch2 = itemView.findViewById(R.id.switch2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(viewPager2.getOrientation() == ViewPager2.ORIENTATION_VERTICAL)
viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
else{
viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
}
}
});
switch2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (switch2.isChecked()) {
button.setEnabled(false);
} else {
button.setEnabled(true);
}
}
});
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/login"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="top|left"
app:tint="#color/white"
android:layout_margin="#dimen/small"
android:layout_marginTop="#dimen/small"
android:src="#drawable/ic_account_circle_24"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHorizontal_bias="0.0"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/screen_viewpager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/tab_indicator"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This will help if you want to place the button on each page you should add it to your activity file and then place it on the position of the view pager
It seems like you are placing a different button on each page in the ViewPager but what you probably want is to place the button in the Activity layout?
Related
I have a recycleView (see picture). You see there are 2 buttons too. Here's the layout file.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_marginLeft="10dp"
android:id="#+id/main_picture"
android:layout_width="45dp"
android:layout_height="50dp"
android:src="#drawable/pfl_img"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/main_picture"
android:layout_marginRight="5dp"
android:layout_marginLeft="10dp"
android:id="#+id/relativeLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edem Palonik"
android:textSize="17sp"
android:id="#+id/textName"
android:textColor="#color/black"
android:layout_above="#+id/textDescription"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profession and ..."
android:textColor="#color/black"
android:textSize="17sp"
android:id="#+id/textDescription"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="20dp"
android:layout_height="18dp"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:id="#+id/historyIcon"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:text="17/12/2017/13:46"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:layout_toEndOf="#+id/historyIcon" />
</RelativeLayout>
<Button
android:id="#+id/call_button"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginRight="10dp"
android:background="#drawable/call_img"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/sms_button" />
<Button
android:id="#+id/sms_button"
android:layout_width="37dp"
android:layout_height="32dp"
android:background="#drawable/sms_img"
android:layout_alignTop="#+id/call_button"
android:layout_alignParentEnd="true" />
<View
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_alignParentBottom="true"
android:background="#color/gray" />
I know, I can use recyclerViewItemCLickListener, but I wanna click on last 2 buttons separately, so what do I need to do?
So I wanna click on last buttons separately, without clicking all line, I want only last buttons to be clickable.
Here's the java code.
public class ConnectionsFragment extends Fragment {
private View mainView;
private RecyclerView recyclerView;
private List<Connections_item> list;
private Button call, sms;
public ConnectionsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.connections_fragment, container, false);
recyclerView = (RecyclerView) mainView.findViewById(R.id.recycler_connection);
ConnectionsAdapter adapter = new ConnectionsAdapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
init(mainView);
return mainView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<>();
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun1", "Inch vor text", R.drawable.missed, "23/11/1998 00:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun2", "Inch vor text", R.drawable.callagain, "24/11/1998 01:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun3", "Inch vor text", R.drawable.missed, "25/11/1998 02:00"));
public void init(View v) {
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
// call.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
// }
// });
// sms.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna send sms?", Toast.LENGTH_SHORT).show();
// }
// });
}
}
Here's the adapter code.
public class ConnectionsAdapter extends RecyclerView.Adapter<ConnectionsAdapter.MyViewHolder> {
Context context;
List<Connections_item> list = new ArrayList<>();
public ConnectionsAdapter(Context context, List<Connections_item> list) {
this.context = context;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate(R.layout.connections_view_item, parent, false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView mainImage, historyImage;
TextView fullName, description, date;
Button call, sms;
public MyViewHolder(View v) {
super(v);
mainImage = (ImageView) v.findViewById(R.id.main_picture);
historyImage = (ImageView) v.findViewById(R.id.historyIcon);
fullName = (TextView) v.findViewById(R.id.textName);
description = (TextView) v.findViewById(R.id.textDescription);
date = (TextView) v.findViewById(R.id.date);
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
}
}
}
Using interface you can achieve this
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
ArrayList<Data> mData;
OnButtonClickListeners onButtonClickListeners;
public TestAdapter(Context mContext, ArrayList<String> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void setOnButtonClickListeners(OnButtonClickListeners listener){
this.onButtonClickListeners = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//Bind holder here
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#Bind(R.id.call_button)
Button btnCall;
#Bind(R.id.sms_button)
Button btnSms;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
btnCall.setOnClickListener(this);
btnSms.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(this.onButtonClickListeners!=null){
switch (v.getId()) {
case R.id.call_button:
onButtonClickListeners.onCallClick(getAdapterPosition());
break;
case R.id.sms_button:
onButtonClickListeners.onSmsClick(getAdapterPosition());
break;
}
}
}
}
public interface OnButtonClickListeners{
void onCallClick(int position);
void onSmsClick(int position);
}
}
Then After you can use the call to this interface from Activity and Fragment like below
private void setUpRecyclerView(){
mAdapter = new ProfileAdapter(mContext,new ArrayList<String>());
lm = new LinearLayoutManager(getActivity());
rvFeeds.setLayoutManager(lm);
rvFeeds.setAdapter(mAdapter);
mAdapter.setOnButtonClickListeners(new OnButtonClickListeners() {
#Override
public void onCallClick(int position) {
//To do your code here
}
#Override
public void onSmsClick(int position) {
//To do your code here
}
})
}
As adapter holds the recyclerView item and buttons are in the item
so all code related to button will be in the adapter only.
In adapter modify the code :
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
}
});
holder.sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna send sms?", }
});
}
In java file just remove call and sms button initialization and listners.
You can try to implement onClickListener to the buttons when you are creating the view in the ViewHolder for the recycler view. Then pass an interface with two methods for two buttons and implement the interface in where ever you require.
Like the example:
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView, ButtonClickListener listner) {
super(itemView);
Button b1 = itemView.findViewById(...);
Button b2 = itemView.findViewById(...);
b1.setOnClickListener(view -> listener.onButton1Click());
b2.setOnClickListener(view -> listener.onButton2Click());
}
}
And now the interface
public interface ButtonClickListener {
void onButton1Click();
void onButton2Click();
}
Otherwise, if you are accustomed with bus you can use instead of using interface. It will make the code much cleaner.
I want to create the following UI with a single list of dataset.
I tried using multiple view type but could not achieve my requirement. I also implemented this blog Android Horizontal and Vertical RecyclerView Example.
But this uses two recyclerviews and there are two sets of data (horizontal data and vertical data).
I also have tried this one. RecyclerView with multiple views using custom adapter in Android
But this is using static card views in XML and loading them in adapter.
I'm beginner in Android development. Please help!
Thank you in advance.
Your desired layout can be achieved by using a GridLayoutManager along with two "item view types" inside your RecyclerView.Adapter.
Here are my layout XML files:
activity_main.xml:
-------------------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
horizontal.xml:
-------------------------
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ccc"/>
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:background="#fff"
android:textColor="#000"
android:textSize="18sp"
android:text="TEXT"/>
</LinearLayout>
</android.support.v7.widget.CardView>
vertical.xml:
-------------------------
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_margin="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ccc"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="center"
android:background="#fff"
android:textColor="#000"
android:textSize="18sp"
android:text="TEXT"/>
</LinearLayout>
</android.support.v7.widget.CardView>
And here is my Java file:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayoutManager manager = new GridLayoutManager(this, 2);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (position % 4) < 2 ? 2 : 1;
}
});
RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setLayoutManager(manager);
recycler.setAdapter(new MyAdapter());
}
private static class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
#Override
public int getItemViewType(int position) {
return (position % 4) < 2
? R.layout.horizontal
: R.layout.vertical;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View itemView = inflater.inflate(viewType, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.image.setImageResource(R.drawable.mouse);
holder.text.setText("" + position);
}
#Override
public int getItemCount() {
return Integer.MAX_VALUE;
}
}
private static class MyViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView text;
public MyViewHolder(View itemView) {
super(itemView);
this.image = (ImageView) itemView.findViewById(R.id.image);
this.text = (TextView) itemView.findViewById(R.id.text);
}
}
}
Let's go over the important parts. First up is the combination of GridLayoutManager and SpanSizeLookup. We're creating the layout manager with this line:
GridLayoutManager manager = new GridLayoutManager(this, 2);
Which means that, by default, there will be two cards in each row of our grid. But then we apply the SpanSizeLookup, which says that half of our rows (found by the statement position % 4 < 2) should actually take up two columns. So we'll have one card, one card, two cards repeating in our "grid".
Then, in the RecyclerView.Adapter class, we override the getItemViewType() method. Here we again use the position % 4 < 2 statement to say that half of our views should be horizontal, and half should be vertical.
getItemViewType() just needs to return any unique int for each view type, so we use a nice trick of returning R.layout constants from this method. Since the view type will then be passed into onCreateViewHolder(), we can use the viewType argument to inflate the correct layout.
And that's it! Not too bad after all. Here's a screenshot of my code in action:
I had this issue not too long ago, though I may not be an expert I think my answer can help you as well. You can do this by creating two different types of layouts, similar to the article. You need to create an abstract class that both of the layout types can extend. Then, in your adapter, check what type of object should be shown.
Abstract class:
public abstract class ListItem {
public static final int TYPE_HORIZONTAL = 0;
public static final int TYPE_VERTICAL = 1;
abstract public int getType();
}
Horizontal Item:
public class HorizontalItem extends ListItem {
private String text;
private Bitmap image;
public HorizontalItem(String text, Bitmap image) {
this.text = text;
this.image = image;
}
/*
* Getter and setter methods here
*/
#Override
public int getType() {
return ListItem.TYPE_HORIZONTAL;
}
}
Vertical Item:
public class VerticalItem extends ListItem {
private String text1;
private Bitmap image1;
private String text2;
private Bitmap image2;
public VerticalItem(String text1, String text2, Bitmap image1, Bitmap image2) {
this.text1 = text1;
this.image1 = image1;
this.text2 = text2;
this.image2 = image2;
}
/*
* Getter and setter methods here
*/
#Override
public int getType() {
return ListItem.TYPE_HORIZONTAL;
}
}
Adapter:
public class ListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<ListItem> listItems;
public static class HorizontalViewHolder extends RecyclerView.ViewHolder {
public TextView text;
public ImageView imageView;
public HorizontalHolder(View v) {
super(v);
text = (TextView) v.findViewById(R.id.text);
imageView = (ImageView) v.findViewById(R.id.imageView);
}
}
public static class VerticalViewHolder extends RecyclerView.ViewHolder {
public TextView text1;
public ImageView imageView1;
public TextView text2;
public ImageView imageView2;
public HorizontalHolder(View v) {
super(v);
text1 = (TextView) v.findViewById(R.id.text1);
imageView1 = (ImageView) v.findViewById(R.id.imageView1);
text2 = (TextView) v.findViewById(R.id.text2);
imageView2 = (ImageView) v.findViewById(R.id.imageView2);
}
}
// constructor
public ListAdapter(ArrayList<ListItem> listItems) {
this.listItems = listItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
RecyclerView.ViewHolder holder = null;
switch (viewType) {
case ListItem.TYPE_HORIZONTAL:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_horizontal, parent, false);
holder = new HorizontalViewHolder(v);
break;
case ListItem.TYPE_VERTICAL:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.template_vertical, parent, false);
holder = new VerticalViewHolder(v);
break;
}
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case ListItem.TYPE_HORIZONTAL:
((HorizontalViewHolder) holder).text.setText(listItems.get(position).getText());
((HorizontalViewHolder) holder).imageView.setImageBitmap(listItems.get(position).getBitmap());
// the getText() and getBitmap() methods come from the getters of the HorizontalItems and VerticalItems that are stored in the ArrayList, listItems
break;
case ListItem.TYPE_DECK:
// Identical to above
break;
}
}
#Override
public int getItemCount() {
return listItems.size();
}
// This is extremely important, it is what lets the adapter know what type each listItem element is
#Override
public int getItemViewType(int position) {
return listItems.get(position).getType();
}
}
Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Must be of abstract type ListItem
ArrayList<ListItem> items = new ArrayList<>();
// populate your ArrayList
items.add(new HorizontalItem("text", bitmap));
items.add(new VerticalItem("text1", "text2", bitmap1, bitmap2));
// ... and so on
ListAdapter adapter = new ListAdapter(items)
RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(this));
// ... the rest of your code below
}
In your layout for the vertical list item, I would just create one file with two halves to it. You can use a LinearLayout to easily divide the subsections into perfect halves.
I have an app I am writing and it is already contains a lot of code, I decided I want to add a navigation drawer to the main activity toolbar but I don't know how to do it without creating a new navigation drawer project and copy my whole project to it which seems like a lot of work, is there a tutorial to add a navigation drawer to an existing project?
Create a layout layout_left_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bgLeftMenu">
<ImageView android:id="#+id/header"
android:src="#drawable/ic_launcher"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="26dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="30dp"
android:layout_marginStart="40dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginTop="26dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/header">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/pressed"/>
<TextView
android:id="#+id/userEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_below="#id/userName"
android:layout_centerInParent="true"
android:textColor="#color/pressed"
android:visibility="gone"/>
</LinearLayout>
</RelativeLayout>
<ListView android:id="#+id/menu_items_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/header"
android:dividerHeight="0dp"
android:divider="#null"
android:background="#color/bgLeftMenu"/>
<ProgressBar android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"/>
</RelativeLayout>
Inflate it in a Custom View:
public class SimpleLeftMenuView extends NavigationView {
private LayoutInflater mInflater;
private Context mContext;
private ListView mItemsList;
private MenuItemsAdapter mItemsAdapter;
private ProgressBar mProgress;
private OnClickMenu mListener;
private ImageView mHeader;
private TextView userName;
private TextView userEmail;
//region Constructors
public SimpleLeftMenuView(Context context) {
super(context);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
public SimpleLeftMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
public SimpleLeftMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
//endregion
private void initLayout(){
mInflater.inflate(R.layout.layout_left_menu, this);
mItemsList = (ListView) findViewById(R.id.menu_items_list);
mProgress = (ProgressBar) findViewById(R.id.progress);
mHeader = (ImageView) findViewById(R.id.header);
userName = (TextView) findViewById(R.id.userName);
userEmail = (TextView) findViewById(R.id.userEmail);
mHeader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
}
public void setSelectedSection(String idSection) {
mItemsAdapter.setLastSelectedSection(idSection);
}
public void setmListener(OnClickMenu mListener) {
this.mListener = mListener;
}
private void setData() {
List<String> sections = new ArrayList<>();
sections.add(mContext.getString(R.string.home_id));
sections.add(mContext.getString(R.string.login_id));
sections.add(mContext.getString(R.string.settings_id));
//.........
//sections.add(mContext.getString(R.string.exit_id));
mItemsAdapter = new MenuItemsAdapter(mContext, sections, new OnClickMenu() {
#Override
public void onClick(String id) {
mItemsAdapter.setLastSelectedSection(id);
if (mListener != null)
mListener.onClick(id);
}
});
mItemsList.setAdapter(mItemsAdapter);
mItemsList.setSelection(0);
mItemsList.setItemChecked(0, true);
}
}
You have to create the MenuItemAdapter.
public class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private static String lastSelectedSection;
private List<String> mSections;
private int currentTextcolor;
private OnClickMenu mListener;
public MenuItemsAdapter(Context context, List<String> sections, OnClickMenu listener) {
mContext = context;
mSections = sections;
mListener = listener;
lastSelectedSection = sections.get(0);
}
#Override
public int getCount() {
return mSections.size();
}
#Override
public String getItem(int position) {
return mSections.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView, ViewGroup parent) {
final MenuItemHolder holder;
if (convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.layout_left_menu_item, parent, false);
holder = new MenuItemHolder(convertView);
convertView.setTag(holder);
}else {
holder = (MenuItemHolder) convertView.getTag();
}
Resources r = mContext.getResources();
int pxMarginSection = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, r.getDisplayMetrics());
holder.position = position;
holder.mLine.setVisibility(View.GONE);
holder.mTitle.setTextColor(mContext.getResources().getColor(R.color.primary));
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
if (mSections.get(position).equals(mContext.getString(R.string.login_id))) {
holder.mIconView.setImageResource(R.drawable.ic_login_gp);
// holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
holder.mTitle.setText(mContext.getString(R.string.action_login));
holder.mLine.setVisibility(View.VISIBLE);
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
} else if (mSections.get(position).equals(mContext.getString(R.string.settings_id))) {
holder.mIconView.setImageResource(R.drawable.option);
holder.mTitle.setText(mContext.getString(R.string.action_settings));
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
holder.mLine.setVisibility(View.VISIBLE);
} else if (mSections.get(position).equals(mContext.getString(R.string.exit_id))) {
holder.mIconView.setImageResource(R.drawable.shutdown);
holder.mTitle.setText(mContext.getString(R.string.salir));
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
holder.mLine.setVisibility(View.VISIBLE);
}
holder.mLayoutItem.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()){
case MotionEvent.ACTION_DOWN:
currentTextcolor = holder.mTitle.getCurrentTextColor();
holder.mLayoutItemSelect.setBackgroundColor(mContext.getResources().getColor(R.color.primary));
holder.mTitle.setTextColor(mContext.getResources().getColor(R.color.text_info));
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.text_info));
return true;
case MotionEvent.ACTION_UP:
holder.mLayoutItemSelect.setBackgroundResource(R.color.bgLeftMenu);
holder.mTitle.setTextColor(currentTextcolor);
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
mListener.onClick(mSections.get(position));
return true;
case MotionEvent.ACTION_CANCEL:
holder.mLayoutItemSelect.setBackgroundColor(mContext.getResources().getColor(R.color.bgLeftMenu));
holder.mTitle.setTextColor(currentTextcolor);
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
return true;
}
return false;
}
});
return convertView;
}
class MenuItemHolder {
// butterKnife
View view;
#Bind(R.id.title)
TextView mTitle;
#Bind(R.id.icon)
ImageView mIconView;
#Bind(R.id.layoutItem)
LinearLayout mLayoutItem;
#Bind (R.id.rl_line)
View mLine;
#Bind(R.id.layoutItemSelect)
LinearLayout mLayoutItemSelect;
int position;
public MenuItemHolder(View itemView) {
ButterKnife.bind(this, itemView);
view = itemView;
}
}
public void setLastSelectedSection(String idSection) {
lastSelectedSection = idSection;
}
}
Now you have to modify your current Activity:
Change your main activity layout to use DrawerLayout and add your custom view "SimpleLeftMenuView":
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#EDEDED">
// YOUR CURRENT LAYOUT
<yourpackage.custom.SimpleLeftMenuView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/bgLeftMenu"/>
</android.support.v4.widget.DrawerLayout>
Activity class:
Add global variables:
protected #Bind(R.id.navigation_view) SimpleLeftMenuView mLeftMenuView;
protected #Bind(R.id.drawerLayout) DrawerLayout mDrawerLayout;
Set onclick listener. You can do an actions depends on the id:
mLeftMenuView.setmListener(new OnClickMenu() {
#Override
public void onClick(String id) {
Log.d("MENU", "ic_menu_hamburger clicked: " + id);
closeDrawer(null);
if (id.equals(getString(R.string.settings_id))) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
MainActivity.this.startActivity(intent);
} else if (id.equals(getString(R.string.exit_id))) {
// salir
showRateDialogBeforeExit();
}
}
});
I have created my own interface OnClickMenu:
public interface OnClickMenu {
void onClick(String id);
}
And add action to open drawer from menu icon:
#Override
public void onBackPressed() {
if((mDrawerLayout) != null && (mDrawerLayout.isDrawerOpen(GravityCompat.START)))
closeDrawer(null);
else {
super.onBackPressed();
}
}
public void closeDrawer(DrawerLayout.DrawerListener listener) {
mDrawerLayout.setDrawerListener(listener);
mDrawerLayout.closeDrawers();
}
public void openDrawer() {
mDrawerLayout.setDrawerListener(null);
mDrawerLayout.openDrawer(GravityCompat.START);
}
Menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
openDrawer();
return true;
}
return super.onOptionsItemSelected(item);
}
add to app build.gradle
compile 'com.android.support:design:26.0.0'
compile 'com.jakewharton:butterknife:8.6.0'
Change all #Bind to #BindView
The easiest way for you would be using this library.
Its really easy to implement and its very flexible.
If you want to do it yourself, consider reading official docs about creating navigation drawer.
I've tried the MaterialDrawer library, as suggested by #yury-dombaev and I have to admit it's far easier to implement than the official Navigation Drawer.
It's possible to implement either with Android X dependencies or with the normal ones.
In my case, since I have the normal ones, I've to stick with the MaterialDrawer 6.0.9v. Although there's a migration guide that I'll give a look.
To implement the library within your current activity do the following:
Add the dependencies in your app build.gradle as explained in Setup 1 of the v 6.0.9 of the library: https://github.com/mikepenz/MaterialDrawer/tree/v6.0.9
Add your drawer in the onCreate() method of your Activity: new DrawerBuilder().withActivity(this).build();.
Now you've got a basic (and useless) lateral menu. So it's time you continue reading the Material Drawer documentation and add menu elements :)
I have been having difficulties making my device register button clicks within an android recyclerview and am not sure why it is not responding as I have looked around and it seems as though it should work. But what I really want to know is if I have put stuff in the wrong place, am I missing something and if so what?
Holder Class
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView time;
public ImageButton button;
public ViewHolder(View v) {
super(v);
time = (TextView)v.findViewById(R.id.time);
button = (ImageButton)v.findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Test", "Button clicked");
}
});
}
}
Adapter Class
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
// WIll hold the timer objects passed through
ArrayList<Timer> lData = null;
// Provide a suitable constructor (depends on the kind of dataset)
public ListAdapter(ArrayList<Timer> myDataset) {
lData = myDataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_adapter, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.time.setText(lData.get(position).getTime());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return lData.size();
}
// Gets the timers
public ArrayList<Timer> getData() {
return lData;
}
}
Main Activity Class (OnCreate Method)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListAdapter(timers);
mRecyclerView.setAdapter(mAdapter);
}
View Item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:layout_margin="6dip"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="fill_vertical"
android:textSize="28sp"
android:text="00:00:00"
android:paddingLeft="10dip"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/imageButton" />
<ImageButton
android:layout_width="50dip"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:src="#drawable/ic_action_pause"/>
</RelativeLayout>
I have a problem with the GridView.
I would like to have a Grid with pictures and under each of them should be a timer. When I click one of the images, there should start the timer bellow of it.
How can I adapt TextViews and Images to a Gridview and let the TextView change every second.
I changed my code now to this
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity implements Runnable{
/** The Constant INTERVALL. */
private static final int INTERVALL = 1000;
private ImageAdapter mAdapter;
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private GridView gridView;
/** The handler. */
private Handler handler = new Handler();
public boolean timerRuns = false;
public int time ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
//GridView gridview = (GridView) findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(this));
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new ImageAdapter(this, listText, listImage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(MainActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public final void run() {
chronometer();
}
public void startTimer(View v) {
timerRuns = true;
time = 5*60;
update();
this.handler.postDelayed(this, INTERVALL);
}
public void stopTimer(View v) {
timerRuns = false;
handler.removeCallbacks(this);
}
public void chronometer(){
time = time -1;
update();
handler.postDelayed(this, INTERVALL);
}
private void update(){
updateScreen();
}
private void updateScreen(){
//TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer);
//tvChronometer.setText(Integer.toString(time));
}
public void prepareList()
{
listText = new ArrayList<String>();
listText.add("Sample");
listText.add("Brazil");
listText.add("Canada");
listText.add("China");
listText.add("France");
listText.add("Germany");
listText.add("Iran");
listText.add("Italy");
listText.add("Japan");
listText.add("Korea");
listText.add("Mexico");
listText.add("Netherlands");
listText.add("Portugal");
listText.add("Russia");
listText.add("Saudi Arabia");
listText.add("Spain");
listText.add("Turkey");
listText.add("United Kingdom");
listText.add("United States");
listImage = new ArrayList<Integer>();
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
}
}
The ImageAdapter
`public class ImageAdapter extends BaseAdapter {
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private Activity activity;
public ImageAdapter(Activity activity,ArrayList<String> listText, ArrayList<Integer> listImage) {
super();
this.listText = listText;
this.listImage = listImage;
this.activity = activity;
}
#Override
public int getCount() {
return listText.size();
}
#Override
public String getItem(int position) {
return listText.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgView;
public TextView txtView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.txtView = (TextView) convertView.findViewById(R.id.eText);
view.imgView = (ImageView) convertView.findViewById(R.id.eImage);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtView.setText(listText.get(position));
view.imgView.setImageResource(listImage.get(position));
return convertView;
}
}`
my gridview
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
and my element.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/eImage"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#color/Bisque" >
</ImageView>
<TextView
android:id="#+id/eText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
I hope you can help me.
1. Creating a gridview with text and image in each cell
Take a look at the documentation for GridView:
http://developer.android.com/guide/topics/ui/layout/gridview.html
The key method there is the public View getView(int position, View convertView, ViewGroup parent)
That method returns a view for each cell in the grid. You can create an XML layout that includes the TextView and ImageView. In the getView method for the adapter inflate the XML layout, attach an onClickListener so you can start the timer and return it as a view.
2. Updating the TextView from the grid
Keep in mind that a gridview contains contains multiple views, each of which can come from the same resource so this: TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer); is not going to work in a gridview.
What you need to do is to get the specific view from the cell that you need (or iterate through all of them) and update the view. Something like this:
//First get the view for the cell assuming it's a composite view
View cellView = (TextView) gridview.getChildAt(position);
//Then get the actual TextView from that grid cell
TextView tvChronometer = cellView.findViewById(R.id.tvChronometer);
Although the best way in my opinion is to save a reference to the TextView when you a creating/instantiating it in the adapter.