After clicking on the Add button it only show the First item. But when I touch the edit text field the remaining items are shown and gone.
Here is the MainActivity:
package com.example.mysecondapp.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
EditText editText;
Button add,ins;
ArrayList<item> list;
Adapter adpter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ins= (Button) findViewById(R.id.button1);
add= (Button) findViewById(R.id.button2);
editText= (EditText) findViewById(R.id.editText2);
recyclerView= (RecyclerView) findViewById(R.id.recycler);
list=new ArrayList<item>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adpter =new Adapter(new ArrayList<item>());
recyclerView.setAdapter(adpter);
ins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String str=editText.getText().toString();
InputMethodManager inputMethodManager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
editText.setText(" ");
Toast.makeText(getBaseContext(),"Added to list",Toast.LENGTH_SHORT).show();
item i=new item(str);
list.add(i);
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adpter.adplist=list;
Toast.makeText(getBaseContext(),"Adding to Recycler View",Toast.LENGTH_SHORT).show();
adpter.notifyDataSetChanged();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
}
Here is the Adapter
package com.example.mysecondapp.myapplication;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter<Adapter.MyHolder> {
ArrayList<item> adplist;
public ArrayList<item> getAdplist() {
return adplist;
}
public void setAdplist(ArrayList<item> adplist) {
this.adplist = adplist;
}
public Adapter(ArrayList<item>list) {
adplist=new ArrayList<item>();
adplist=list;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
return new MyHolder(v);
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
item i=adplist.get(position);
holder.tv.setText(i.getStr());
}
#Override
public int getItemCount() {
return adplist.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView tv;
public MyHolder(View itemView) {
super(itemView);
tv=itemView.findViewById(R.id.item_text_view);
}
}
}
Here is The item
package com.example.mysecondapp.myapplication;
public class item {
String str;
public item(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
Here is activity xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.mysecondapp.myapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Here is content xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main"
tools:context="com.example.mysecondapp.myapplication.MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText2"
android:layout_weight="1" />
<Button
android:text="INSERT"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/button1"
android:layout_weight="2" />
<Button
android:text="ADD"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/button2"
android:layout_weight="2" />
</LinearLayout>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"/>
</RelativeLayout>
And the item 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">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/item_text_view"/>
</LinearLayout>
What's wrong with the code ?
Thanks in advance
Try this:
i have changed layout_height of LinearLayout to wrap_content
item.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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/item_text_view"/>
</LinearLayout>
The problem is that you have set the height of the recycler item to match parent which means that the first item of your recycler view is taking the full screen. If you scroll you will find the other items at the bottom.
To fix this
In item.xml use
<?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="wrap_content">
Instead of
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
Related
I am totally new in the world of Android development and have some trouble to understand how a RecycleViewAdapter works with a CardView when the CardView is a Fragment. I was trying to understand the example on https://github.com/firebase/quickstart-android/blob/master/database/README.md but since they are using a lot of stuff which is related to Firebase I tried to port this to my own example.
I want to have a list which contains several cards just like this:
However, the user should be able to add and remove different cards. At the beginning the view should be empty and if the user press the floating button on the right corner
a new card should be created.
I've just ported the way I thought it should work. Unfortunately, when I press the button nothing is happening (of course the Hello World is printed).
Thanks for you help.
Here is the code of my MainActivity:
package com.example.dynamicfragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity
{
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("Hello World");
fragmentTransaction.add(new CardListFragment(), "CardListFragment");
}
});
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the class who extend the CardListFragment:
package com.example.dynamicfragment;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.dynamicfragment.adapter.CardAdapter;
import com.example.dynamicfragment.model.Party;
import java.util.ArrayList;
public class CardListFragment extends Fragment
{
private static final String TAG = "CardListFragment";
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
private CardAdapter mAdapter;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_card_list, container, false);
mRecycler = rootView.findViewById(R.id.messagesList);
mRecycler.setHasFixedSize(true);
ArrayList<Party> demo = new ArrayList<>();
demo.add(new Party(0,"Demo", R.drawable.ic_action_account_circle_40));
this.mAdapter = new CardAdapter(demo);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
mRecycler.setAdapter(null);
}
#Override
public void onStart()
{
super.onStart();
if (null != mAdapter)
{
//mAdapter.startListening();
}
}
#Override
public void onStop()
{
super.onStop();
if (null != mAdapter)
{
//mAdapter.stopListening();
}
}
}
Here is the code of my data model:
package com.example.dynamicfragment.model;
import java.util.Objects;
public class Party
{
private int id;
private String name;
private int image;
public Party(int id, String name, int image)
{
this.id = id;
this.name = name;
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
#Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Party party = (Party) o;
return id == party.id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
}
Here is my Adapater class:
package com.example.dynamicfragment.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.dynamicfragment.R;
import com.example.dynamicfragment.model.Party;
import java.util.ArrayList;
public class CardAdapter extends RecyclerView .Adapter<CardAdapter.CardViewHolder>
{
private ArrayList<Party> dataList;
public static class CardViewHolder extends RecyclerView.ViewHolder
{
TextView partyName;
ImageView imageViewIcon;
public CardViewHolder(View itemView)
{
super(itemView);
this.partyName = (TextView) itemView.findViewById(R.id.postAuthor);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.postAuthorPhoto);
}
}
public CardAdapter(ArrayList<Party> data)
{
this.dataList = data;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
return new CardViewHolder(view);
}
#Override
public void onBindViewHolder(final CardViewHolder holder, final int listPosition)
{
TextView partyName = holder.partyName;
ImageView imageView = holder.imageViewIcon;
partyName.setText(dataList.get(listPosition).getName());
imageView.setImageResource(dataList.get(listPosition).getImage());
}
#Override
public int getItemCount()
{
return dataList != null ? dataList.size() : 0;
}
}
Content files:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<include layout="#layout/fragment_card_list" />
</android.support.constraint.ConstraintLayout>
fragment_card_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/messagesList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:padding="5dp"
android:scrollbars="vertical"
tools:listitem="#layout/card_view" />
</FrameLayout>
card_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<include
android:id="#+id/postAuthorLayout"
layout="#layout/include_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<LinearLayout
android:id="#+id/starLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/postAuthorLayout"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/postAuthorLayout"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:background="?attr/selectableItemBackground"
android:src="#drawable/ic_toggle_star_outline_24" />
<TextView
android:id="#+id/postNumStars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
tools:text="7" />
</LinearLayout>
<include layout="#layout/include_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/postAuthorLayout"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
include_post_author.xml:
<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/postAuthorPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_action_account_circle_40" />
<TextView
android:id="#+id/postAuthor"
style="#style/Base.TextAppearance.AppCompat.Small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
tools:text="someauthor#email.com" />
</LinearLayout>
include_post_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/postTitle"
style="#style/TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textStyle="bold"
tools:text="My First Post" />
<TextView
android:id="#+id/postBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
tools:text="Hallo Welt" />
</LinearLayout>
#Christoph M. The Fragment Transaction if you want to applu on ui u need to give a FrameLayout Id.
Create a FrameLayout with one id in your main class then attach your fragment to id value
like this below
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
FirstFragment fragment = new FirstFragment();
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, fragment);
transaction.addToBackStack(ConstantVariables.FirstFragment);
transaction.commit();
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I am a bit comfused at this moment. In order to save time I used Android Studio's template for Navigation Drawer Activity. I was planning to create a Navigation Drawer and pass it through the rest of the activities. The first Activity did go well. The problem is with the second one, as I want to have the Navigation Drawer and create a RecyclerView.
So my code is:
Content_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.sparrowred.sendcard.Main2Activity"
tools:showIn="#layout/activity_main2">
<android.support.v7.widget.RecyclerView
android:id="#+id/imageRecycleView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
app_bar_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.sparrowred.sendcard.Main2Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main2" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_menu_add" />
</android.support.design.widget.CoordinatorLayout>
nav_header_main2.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="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="#style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
image_list_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:contentDescription="#string/image_descrprtion"
android:layout_gravity="center_horizontal"
android:id="#+id/imageId"
android:src="#drawable/profile"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/title"
android:textStyle="bold"
android:padding="8dp"
android:layout_gravity="center_horizontal"
android:text="dummy"/>
</LinearLayout>
imageAdapter.java:
package com.sparrowred.sendcard;
public class imageAdapter {
private String title;
private int imageId;
public imageAdapter() {
}
public imageAdapter(String title, int imageId) {
this.title = title;
this.imageId = imageId;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setImageId(int imageId){
this.imageId = imageId;
}
public int getImageId(){
return this.imageId;
}
}
imageDescriptionArray.java (I need to change the name :P):
package com.sparrowred.sendcard;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class imageDescriptionArray extends RecyclerView.Adapter<imageDescriptionArray.MyViewHolder> {
private LayoutInflater layoutInflater;
private List<imageAdapter> imageAdapterList;
public imageDescriptionArray(List<imageAdapter> imageAdapterList) {
this.imageAdapterList = imageAdapterList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.image_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
imageAdapter iva = imageAdapterList.get(position);
holder.title.setText(iva.getTitle());
holder.image.setImageResource(iva.getImageId());
}
#Override
public int getItemCount() {
return imageAdapterList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public ImageView image;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
image = (ImageView) view.findViewById(R.id.imageId);
}
}
}
and finally Main2Activity.java:
package com.sparrowred.sendcard;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.recyclerview.animators.SlideInUpAnimator;
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView mImageRecycleView;
private List<imageAdapter> imageAdapterList;
private imageDescriptionArray mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mImageRecycleView = (RecyclerView) findViewById(R.id.imageRecycleView);
mImageRecycleView.setHasFixedSize(true);
imageAdapterList = new ArrayList<>(12);
mAdapter = new imageDescriptionArray(imageAdapterList);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mImageRecycleView.setLayoutManager(mLayoutManager);
mImageRecycleView.setItemAnimator(new SlideInUpAnimator());
mImageRecycleView.setAdapter(mAdapter);
prepareData();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void prepareData(){
List<imageAdapter> data = new ArrayList<>();
int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i mage_7,R.drawable.birthday_image_8,
R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_ image_11,R.drawable.birthday_image_12};
String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
"retro","perspective","flying presents","empty card","giving a present","tasty cake"};
for(int i = 0; i<images.length && i<description.length; i++){
imageAdapter current = new imageAdapter();
current.setTitle(description[i]);
current.setImageId(images[i]);
data.add(current);
}
mAdapter.notifyDataSetChanged();
}
}
This the code for my second activity.It's not fully implemented but for sure the recyclerView doesn't work. Can anyone help me out with this. I believe that the problem is within my xmls .... but I cannot find anything.
PS. My code, when compiled shows no errors....
Try with the following code. Replace your prepareData() with mine
private void prepareData(){
int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i mage_7,R.drawable.birthday_image_8,
R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_ image_11,R.drawable.birthday_image_12};
String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
"retro","perspective","flying presents","empty card","giving a present","tasty cake"};
for(int i = 0; i<images.length && i<description.length; i++){
imageAdapter current = new imageAdapter();
current.setTitle(description[i]);
current.setImageId(images[i]);
imageAdapterList.add(current);
}
mAdapter.notifyDataSetChanged();
}
Here is the problem: I create the simplest RecyclerView in the world, but it displays only the first item. I cannot understand why. Thanks for any help.
item_layout.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="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tv_detail"/>
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.bcit.moonlady.testrecycler.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="#+id/tv_hello"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="#+id/rv_details"
android:layout_below="#+id/tv_hello"/>
</RelativeLayout>
MainActivity.java
package com.bcit.moonlady.testrecycler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
String[] data = {"test1", "test2", "test3"};
RecyclerView mRecView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecView = (RecyclerView)findViewById(R.id.rv_details);
mRecView.setHasFixedSize(true);
mRecView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mRecView.setAdapter(new DetailAdapter());
}
private class DetailView extends RecyclerView.ViewHolder {
TextView mTextView;
public DetailView(View itemView) {
super(itemView);
mTextView = (TextView)itemView.findViewById(R.id.tv_detail);
}
public void bindView(String string) {
mTextView.setText(string);
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailView> {
#Override
public DetailView onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.item_layout, parent, false);
return new DetailView(v);
}
#Override
public void onBindViewHolder(DetailView holder, int position) {
String string = data[position];
holder.bindView(string);
}
#Override
public int getItemCount() {
return data.length;
}
}
}
You need to change your item_layout height as wrap_content
if your are using Android Support Library v 23.2.0 and above
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tv_detail"/>
</RelativeLayout>
I too made this common mistake. Just change your parent LinearLayout - height should be "wrap_content"
<LinearLayout
android:layout_width="match_parent"
android:layout_height = "wrap_content"
..... >
..
..
</LinearLayout>
I had same problem, when RecyclerView was wrapped in ScrollView. You should use NestedScrollView instead.
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- other content -->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
Set the height to wrap_content of the RelativeLayout in the item_layout.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="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tv_detail"/>
</RelativeLayout>
it may help
customAdapter = new CustomRecycleradapter(arrItems);
recyclerView.setLayoutManager(new LinearLayoutManager(mParentActivity));
recyclerView.setAdapter(customAdapter);
ArrayList<ListofItems> mSource;
// adapter class
public CustomRecycleradapter(ArrayList<ListofItems> source) {
this.mSource = source;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new CustomHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof CustomHolder) {
((CustomHolder) holder).customerName.setText(mSource.get(position).getCustomerNumber());
}
}
#Override
public int getItemCount() {
return mSource.size();
}
public void addItem(ArrayList<ListofItems> itemLists) {
mSource.addAll(itemLists);
notifyItemInserted(mSource.size() - 1);
}
public class CustomHolder extends RecyclerView.ViewHolder {
#Bind(R.id.customer_name)
TextView customerName;
#Bind(R.id.time_stamp)
TextView timeStamp;
#Bind(R.id.amount)
TextView amount;
public CustomHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Activity:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecycler;
String[] data = {"test1", "test2", "test3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecycler = (RecyclerView) findViewById(R.id.rv_details);
DetailAdapter adapter = new DetailAdapter();
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(manager);
mRecycler.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
private class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailView> {
#Override
public void onBindViewHolder(DetailView holder, int position) {
String string = data[position];
holder.bindView(string);
}
#Override
public DetailView onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.item_layout, parent, false);
return new DetailView(v);
}
#Override
public int getItemCount() {
return data.length;
}
class DetailView extends RecyclerView.ViewHolder {
TextView mTextView;
public DetailView(View itemView) {
super(itemView);
mTextView = (TextView)itemView.findViewById(R.id.tv_detail);
}
public void bindView(String string) {
mTextView.setText(string);
}
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv_details"
/>
</RelativeLayout>
item_layout.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="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/tv_detail"/>
</RelativeLayout>
First up, u should put your Recyclerview.veiwholder class inside the adapter to ensure youre getting the same instance.
//replaces contents of a view, invoked by the layout manager
#Override public void onBindViewHolder(ViewHolder holder, int position) {
// get the message to display from the array at the specified position
// replace contents of the view with the new element
holder.mytextview.setText(recieveHistory.get(position));
}
It uses retrofit 2.0 to fetch the data from the webservice and bind it to the card view. When I click on the card view having image and textviews, on click is not triggering, rather a strange behaviour is at the very corner edges of the card view onclick is triggering.
Item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
card_view:cardCornerRadius="1dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
android:layout_margin="5dp"
android:clickable="true">
<ImageView
android:id="#+id/flowerImage"
android:layout_width="match_parent"
android:layout_height="200dp"
android:focusable="true"
android:clickable="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="visible"/>
<ImageButton
android:id="#+id/favIcon"
android:layout_width="32dp"
android:layout_height="32dp"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"
android:background="#drawable/ic_favorite_border"
android:focusable="true"
android:clickable="true"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/flowerImage"
android:orientation="vertical"
>
<TextView
android:id="#+id/flowerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textColor="#color/colorPrimary"
android:textAppearance="?android:attr/textAppearanceMedium"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:layout_alignBottom="#id/flowerName"
android:textAppearance="?android:attr/textAppearanceSmall"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/flowerCategory"
android:text="New Text"
android:focusable="true"
android:clickable="true"
android:visibility="visible"/>
<TextView
android:id="#+id/flowerInstruction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="New Text"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Content_main.xml
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</LinearLayout>
Main Activity Layout file
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:elevation="8dp"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The code base is following MVC design pattern. Controller does the job of getting the web service data
MainActivity.java
package com.innovation.myapp.jwelleryonrent.View;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.controller.jwelleryController;
import com.innovation.myapp.jwelleryonrent.model.adapter.CustomItemClickListner;
import com.innovation.myapp.jwelleryonrent.model.adapter.JwelleryAdapter;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements jwelleryController.JwelleryCallbackListener {
private Toolbar mToolbar;
private RecyclerView mRecyclerView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private List<JwelleryCollection> mJwelleryList = new ArrayList<>();
private JwelleryAdapter mJwelleryAdapter;
private jwelleryController mController;
private boolean isInFavourites = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configToolbar();
mController = new jwelleryController(MainActivity.this);
configViews();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.item_row, container, false);
ImageButton imgBtn = (ImageButton) findViewById(R.id.favIcon);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addItemToBag(v);
}
});
return rootView;
}
private void addItemToBag(View v)
{
isInFavourites = true;
ImageButton btnFaviourite = (ImageButton) findViewById(R.id.favIcon);
if(isInFavourites==true) {
btnFaviourite.setImageResource(R.drawable.ic_favorite_white_24dp);
}
else
btnFaviourite.setImageResource(R.drawable.ic_favorite_border);
Snackbar.make(v, "Item added to Favourites", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
private void configToolbar() {
mToolbar = (Toolbar) this.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
private void initializeAdapter()
{
mJwelleryAdapter = new JwelleryAdapter(mJwelleryList, new CustomItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Toast.makeText(MainActivity.this, "Clicked Item: "+position,Toast.LENGTH_LONG).show();
}
});
mRecyclerView.setAdapter(mJwelleryAdapter);
mSwipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorAccent),
getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mController.startFetching();
}
});
}
private void configViews() {
mRecyclerView = (RecyclerView) this.findViewById(R.id.list);
mSwipeRefreshLayout = (SwipeRefreshLayout) this.findViewById(R.id.swipe);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
mController.startFetching();
initializeAdapter();
// mJwelleryAdapter= new JwelleryAdapter(mJwelleryList);
}
#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);
}
#Override
public void onFetchStart() {
}
#Override
public void onFetchProgress(JwelleryCollection jwellery) {
mJwelleryAdapter.addJwellery(jwellery);
}
#Override
public void onFetchProgress(List<JwelleryCollection> jwelleryList) {
}
#Override
public void onFetchComplete() {
mSwipeRefreshLayout.setRefreshing(false);
}
#Override
public void onFetchFailure() {
}
}
Recycler view uses the adapter view holder pattern to initialize the adapter
JwelleryAdapter class
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.innovation.myapp.jwelleryonrent.R;
import com.innovation.myapp.jwelleryonrent.View.MainActivity;
import com.innovation.myapp.jwelleryonrent.model.pojo.JwelleryCollection;
import com.innovation.myapp.jwelleryonrent.model.utilities.Constants;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
*
*/
public class JwelleryAdapter extends RecyclerView.Adapter<JwelleryAdapter.Holder> {
private List<JwelleryCollection> mJwelleryCollection;
CustomItemClickListner itemListner;
Context mContext;
public JwelleryAdapter(List<JwelleryCollection> jwellery) {
mJwelleryCollection = jwellery;
}
public JwelleryAdapter( List<JwelleryCollection> jwellery,CustomItemClickListner listner) {
mJwelleryCollection = jwellery;
this.itemListner = listner;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false);
final Holder mViewHolder = new Holder(row);
row.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
itemListner.onItemClick(v,mViewHolder.getPosition());
}
});
return mViewHolder;
}
#Override
public void onBindViewHolder(JwelleryAdapter.Holder holder, int position) {
JwelleryCollection currentJwellery = mJwelleryCollection.get(position);
holder.mName.setText(currentJwellery.mName);
holder.mCategory.setText(currentJwellery.mCategory);
holder.mPrice.setText(Double.toString(currentJwellery.mPrice));
holder.mInstructions.setText(currentJwellery.mInstructions);
Picasso.with(holder.itemView.getContext()).load(Constants.PHOTO_URL + currentJwellery.mPhoto).into(holder.mImage);
}
public void addJwellery(JwelleryCollection jwellery) {
mJwelleryCollection.add(jwellery);
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return mJwelleryCollection.size();
}
public class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
Context contxt;
public TextView mName, mCategory, mPrice, mInstructions;
public ImageView mImage;
public Holder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.flowerImage);
mName = (TextView) itemView.findViewById(R.id.flowerName);
mCategory = (TextView) itemView.findViewById(R.id.flowerCategory);
mPrice = (TextView) itemView.findViewById(R.id.flowerPrice);
mInstructions = (TextView) itemView.findViewById(R.id.flowerInstruction);
}
public Holder(View itemView,int ViewType,Context c) {
// Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
contxt = c;
itemView.setClickable(true);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(contxt, "The Item Clicked is: " + getPosition(), Toast.LENGTH_SHORT).show();
}
}
}
CustomerItemClickListner Interface to handle row item on click
package com.innovation.myapp.jwelleryonrent.model.adapter;
import android.view.View;
/**
*
*/
public interface CustomItemClickListner {
public void onItemClick(View v,int position);
}
First create one variable of your interface in your adapter:
CustomItemClickListener mListener;
then like you have set in your OnClick() method:
if (mListener != null) {
mListener.onItemClick(v, getAdapterPosition());
}
and the last thing you need to modify in your adapter is creating new method which you will call later in your activity class for handling listener:
public void setOnItemClickListener(CustomItemClickListener listener) {
mListener = listener;
}
now you can call this method in your activity like this:
adapter.setOnItemClickListener(this); // implement interface
// or
adapter.setOnItemClickListener(new CustomItemClickListener());
I'm doing trying to recreate whatsapp's layout using android and this is what i have so far
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/message_pane"
android:layout_height="wrap_content"
android:minHeight="300dp"
android:layout_width="match_parent"
android:foregroundGravity="fill">
</FrameLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:id="#+id/linearLayout">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/edit_text"
android:id="#+id/edit_text" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send_text"
android:onClick="sendMessage"/>
</LinearLayout>
</RelativeLayout>
And this is what my java file looks like
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
EditText message = (EditText) findViewById(R.id.edit_text);
TextView text = new TextView(this);
text.setText(message.getText());
FrameLayout msgs = (FrameLayout) findViewById(R.id.message_pane);
msgs.addView(text);
}
}
When i click on send, the message does appear on the FrameLayout, but the next one's all go to the same location.
I would like to know how to make them go below previous messages and if there are any better layouts i can use to implement Whatsapp's layout.
Thanks.
Haha, got it working at last, i was able to use uiautomatorviewer (suggested by CommonsWare) to view their structure.
It turns out i has to implement a custom adapter in addition to a Listview to get it working, here's the code in case anyone is interested.
MessageAdapter.java
package com.example.mestchat.Adapter;
/**
* Created by elimence on 6/1/13.
*/
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.mestchat.MessageData;
import com.example.mestchat.R;
public class MessageAdapter extends ArrayAdapter {
private final Activity activity;
private final List messages;
public MessageAdapter(Activity activity, List objs) {
super(activity, R.layout.message_list , objs);
this.activity = activity;
this.messages = objs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
MessageView msgView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.message_list, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
msgView = new MessageView();
msgView.msg = (TextView) rowView.findViewById(R.id.message_text);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(msgView);
} else {
msgView = (MessageView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
MessageData currentMsg = (MessageData)messages.get(position);
msgView.msg.setText(currentMsg.getMessage());
return rowView;
}
protected static class MessageView {
protected TextView msg;
}
}
MessageData.java
package com.example.mestchat;
/**
* Created by elimence on 6/1/13.
*/
public class MessageData {
private String message;
public MessageData(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
package com.example.mestchat;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.mestchat.Adapter.MessageAdapter;
import com.example.mestchat.REST.RestWebServices;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
MessageAdapter adapter;
List msgs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgs = new ArrayList();
adapter = new MessageAdapter(this, msgs);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendMessage(View view) {
EditText message = (EditText) findViewById(R.id.enter_message);
String mText = message.getText().toString();
msgs.add(new MessageData(mText));
adapter.notifyDataSetChanged();
message.setText("");
}
}
message_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:gravity="fill_horizontal"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:textColor="#color/black"
android:background="#color/white"
android:id="#+id/message_text" />
</RelativeLayout>
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<!--<FrameLayout-->
<!--android:background="#color/header_color"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="0dp"-->
<!--android:layout_weight="1">-->
<!--</FrameLayout>-->
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="0dp"
android:layout_weight="10">
<FrameLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="11">
<ListView
android:id="#android:id/list"
android:background="#drawable/background"
android:drawSelectorOnTop="false"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:footerDividersEnabled="true">
</ListView>
</FrameLayout>
<FrameLayout
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1">
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#color/send_box_color"
android:id="#+id/linearLayout">
<EditText
android:id="#+id/enter_message"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:hint="#string/edit_text" />
<Button
android:id="#+id/send_button"
android:layout_width="45dp"
android:layout_height="30dp"
android:background="#drawable/send_btn"
android:onClick="sendMessage"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</LinearLayout>