I took this tutorial as reference.
Despite of checking everything, no data is appearing on screen ie. main_activity. I've already referred to other pages on stackoverflow regarding this issue. Can't find a viable solution.
NOTE: There is no warning or error while I deploy app on the device.
This is the source code.
MainActivity.java:
public class MainActivity extends Activity
{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
mRecyclerView.addItemDecoration(itemDecoration);
// Code to Add an item with default animation
DataObject obj = new DataObject("red", "foo");
((MyRecyclerViewAdapter) mAdapter).addItem(obj, 0);
// Code to remove an item with default animation
//((MyRecyclerViewAdapter) mAdapter).deleteItem(index);
}
#Override
protected void onResume() {
super.onResume();
((MyRecyclerViewAdapter) mAdapter).setOnItemClickListener(new MyRecyclerViewAdapter.MyClickListener()
{
#Override
public void onItemClick(int position, View v) {
Toast.makeText(MainActivity.this, "Clicked item: " + position, Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<DataObject> getDataSet() {
ArrayList results = new ArrayList<DataObject>();
for (int index = 0; index < 20; index++){
DataObject obj = new DataObject("Some Primary Text " + index, "Secondary " + index);
results.add(index, obj);
}
return results;
}
}
DataObject.java:
public class DataObject {
private String mText1;
private String mText2;
DataObject (String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
MyRecyclerViewAdapter.java:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder>
{
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<DataObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView label;
TextView dateTime;
public DataObjectHolder(View itemView)
{
super(itemView);
label = (TextView) itemView.findViewById(R.id.textView);
dateTime = (TextView) itemView.findViewById(R.id.textView2);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getPosition(), v);
}
}
public void setOnItemClickListener(MyClickListener myClickListener) {
this.myClickListener = myClickListener;
}
public MyRecyclerViewAdapter(ArrayList<DataObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.label.setText(mDataset.get(position).getmText1());
holder.dateTime.setText(mDataset.get(position).getmText2());
}
public void addItem(DataObject dataObj, int index) {
mDataset.add(dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mDataset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount()
{
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
}
DividerIconDecoration.java
public class DividerItemDecoration extends RecyclerView.ItemDecoration{
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
#Override
public void onDraw(Canvas c, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
#Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</RelativeLayout>
</ScrollView>
recyclerview_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"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingTop="5dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
The problem is in activity_main.xml. You should remove ScrollView and it will work (There's no reason to have one since the recyclerview has an implicit one). There is no scrollview in the tutorial either: check activity_recycler_view.xml.
Related
I have a RecyclerView and an adapter which has an ArrayList of Person model.
When the app starts I type the names in the EditText and press the button:
1)
2)
3)
4)
But when I log personList data in the activity, the result is:
personList: Item 0 -----> Alireza
personList: Item 1 -----> Tohid
personList: Item 2 -----> Alireza
First item is removed and last item is repeated in the first one. (My adapter is more complex, but I have reduced the code and views to focus on the main problem)
Adapter Layout:
<?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"
android:orientation="vertical">
<TextView
android:id="#+id/tv_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
Adapter Class:
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private ArrayList<Person> mList;
private View.OnClickListener listener;
public TestAdapter(ArrayList<Person> mList, View.OnClickListener listener) {
this.mList = mList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.test_adapter_item, parent, false);
if (viewType == Person.State.FIRST.getValue()) {
return new FirstViewHolder(itemView);
} else { // if (viewType == Person.State.SECOND.getValue())
return new SecondViewHolder(itemView);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
final int pos = holder.getAdapterPosition();
final Person person = mList.get(pos);
if (holder instanceof FirstViewHolder) {
final FirstViewHolder h = (FirstViewHolder) holder;
h.tvName.setVisibility(View.GONE);
h.etName.setVisibility(View.VISIBLE);
h.etName.setText("");
h.etName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
person.setFirstName(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
h.btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
person.setState(Person.State.SECOND);
notifyItemChanged(pos);
listener.onClick(v);
}
});
} else { // if (holder instanceof SecondViewHolder)
final SecondViewHolder h = (SecondViewHolder) holder;
h.tvName.setVisibility(View.VISIBLE);
h.tvName.setText(person.getFirstName());
h.etName.setVisibility(View.GONE);
h.btnAccept.setVisibility(View.GONE);
}
}
private static class FirstViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private EditText etName;
private Button btnAccept;
private FirstViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
etName = itemView.findViewById(R.id.et_name);
btnAccept = itemView.findViewById(R.id.button);
}
}
private static class SecondViewHolder extends RecyclerView.ViewHolder {
private TextView tvName;
private EditText etName;
private Button btnAccept;
SecondViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tv_name);
etName = itemView.findViewById(R.id.et_name);
btnAccept = itemView.findViewById(R.id.button);
}
}
#Override
public int getItemCount() {
return mList.size();
}
#Override
public int getItemViewType(int position) {
return mList.get(position).getState().getValue();
}
}
Related Part of Activity:
ArrayList<Person> personList = new ArrayList<>();
personList.add(new Person("", Person.State.FIRST));
adapter = new TestAdapter(personList, new View.OnClickListener() {
#Override
public void onClick(View v) {
if (personList.size() < 3) {
personList.add(new Person("", Person.State.FIRST));
adapter.notifyItemInserted(personList.size());
} else {
for (int i = 0; i < personList.size(); i++) {
Log.i("personList", "Item " + i + " -----> " + personList.get(i).getName());
}
}
}
});
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
What's the problem? And how can I achieve correct and real ArrayList Data?
your problem lies with addTextChangedListener, when new items are added in recycler view old TextChangedListeners arent removed. and they keep changing your list items values. you should remove those listeners when state is changed to SECOND state(which is surprisingly tricky look at this How to remove all listeners added with addTextChangedListener). or you should add this validation when onTextChanged is triggered. if (person.getState() == Person.State.FIRST)
person.setFirstName(s.toString());
So, I have a three items in a recyclerview and I want to check if one of the field is unique or not in my case it's name. all the fields are shown correctly on the screen but whenever I call checkValidation it always returns false even when two names are not the same. I have a list and whenever I call from the activity it shows some different values as not how it is on the screen. If there is anything you didn't get kindly please comment.
dear community I really need help here..
Let me know what part you really didn't get.. :/
MainActivity.java
public MainActivity extends AppCompatActivity implements someinterface
..
..
#OnClick(R.id.activity_detailed_proceed)
void goToOrderPage() {
if (checkValidation()) {
startActivity(new Intent(MainActivity.this, Destination.class));
} else {
SameNameAlertDialogFragment sameNameAlertDialogFragment = new SameNameAlertDialogFragment();
sameNameAlertDialogFragment.show(getSupportFragmentManager(), "ERROR DIALOG");
}
}
..
..
boolean checkValidation() {
//
ArrayList<PersonFriends> personList = personAdapter.getPersonList();
ArrayList<String> namesList = new ArrayList<>();
for (int i = 0; i < personList.size(); i++) {
namesList.add(personList.get(i).getName());
System.out.println(personList.get(i).getName());
}
boolean corrent = true;
Set<String> set = new HashSet<String>(namesList);
if (set.size() < namesList.size()) {
//duplicates found
Log.d(TAG, "False was called here");
return false;
}
return true;
}
PersonAdapter personAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_selected_therapy);
ButterKnife.bind(this);
ArrayList<PersonFriends> personList = new ArrayList<>();
personAdapter = new PersonAdapter(this, this);
personRecyclerview.setAdapter(personAdapter);
personRecyclerview.setNestedScrollingEnabled(false);
personRecyclerview.setLayoutManager(new LinearLayoutManager(this));
}
some interface setup to get the name and duration
#Override
public void onPersonDetailClicked(int position, View view) {
if (view.getId() == R.id.person_name) {
adapterPosition = position;
EnterPersonDialogFragment enterPersonDialogFragment = new EnterPersonDialogFragment();
enterPersonDialogFragment.show(getSupportFragmentManager(), "PERSONS SELECTED");
}
if (view.getId() == R.id.delete_person) {
personAdapter.removeItem(position);
// personAdapter.setPersonList(personList);
// personAdapter.notifyItemRemoved(position);
}
if (view.getId() == R.id.person_duration) {
adapterPosition = position;
DurationDialogFragment durationDialogFragment = new DurationDialogFragment();
durationDialogFragment.show(getSupportFragmentManager(), "DURATION SELECTED");
}
}
#Override
public void enteredInName(String name) {
//change the list that is inside the adapter.
personAdapter.getPersonList().get(adapterPosition).setName(name);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_NAME);
}
#Override
public void durationSelectedIs(String duration) {
personAdapter.getPersonList().get(adapterPosition).setduration(duration);
personAdapter.notifyItemChanged(adapterPosition, PersonAdapter.PAYLOAD_DURATION);
}
PersonAdapter.java
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.PersonViewHolder> {
public static final String PAYLOAD_NAME = "PAYLOAD_NAME";
public static final String PAYLOAD_DURATION = "PAYLOAD_DURATION";
public static final String PAYLOAD_DATE = "PAYLOAD_DATE";
public static final String TAG = PersonAdapter.class.getSimpleName();
Context context;
ArrayList<PersonFriends> personList;
onPersonItemClicked onPersonItemClicked;
public PersonAdapter(Context context, onPersonItemClicked personItemClickListener) {
this.context = context;
onPersonItemClicked = personItemClickListener;
}
public void setPersonList(ArrayList<PersonFriends> personList) {
this.personList = personList;
notifyDataSetChanged();
}
public ArrayList<PersonFriends> getPersonList() {
return this.personList;
}
public void removeItem(int position) {
personList.remove(position);
notifyItemRemoved(position);
}
#NonNull
#Override
public PersonAdapter.PersonViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.item_persons_details, parent, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PersonAdapter.PersonViewHolder holder, int position) {
PersonFriends Person = personList.get(position);
holder.personName.setText(Person.getName());
holder.personDate.setText(Person.getDate());
holder.personDuration.setText(Person.getduration());
if (position == 0) {
holder.deleteFab.hide();
}
}
#Override
public void onBindViewHolder(#NonNull PersonViewHolder holder, int position, #NonNull List<Object> payloads) {
if (!payloads.isEmpty()) {
final PersonFriends item = personList.get(position);
for (final Object payload : payloads) {
if (payload.equals(PAYLOAD_NAME)) {
// in this case only name will be updated
holder.personName.setText(item.getName());
} else if (payload.equals(PAYLOAD_DURATION)) {
// only age will be updated
holder.personDuration.setText(item.getduration());
} else if (payload.equals(PAYLOAD_DATE)) {
holder.personDate.setText(item.getDate());
}
}
} else {
// in this case regular onBindViewHolder will be called
super.onBindViewHolder(holder, position, payloads);
}
}
#Override
public int getItemCount() {
return personList.size();
}
public interface onPersonItemClicked {
void onPersonDetailClicked(int position, View view);
}
class PersonViewHolder extends RecyclerView.ViewHolder {
private final View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
onPersonItemClicked.onPersonDetailClicked(getAdapterPosition(), view);
}
};
#BindView(R.id.person_name)
TextView personName;
#BindView(R.id.person_date)
TextView personDate;
#BindView(R.id.person_duration)
TextView personDuration;
#BindView(R.id.delete_person)
FloatingActionButton deleteFab;
public PersonViewHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
personName.setOnClickListener(onClickListener);
personDate.setOnClickListener(onClickListener);
personDuration.setOnClickListener(onClickListener);
deleteFab.setOnClickListener(onClickListener);
}
}
}
item_persons_details.xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|top"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="24dp"
android:background="#drawable/bg_rounded_30"
android:padding="8dp"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="NAME">
</TextView>
<TextView
android:id="#+id/person_duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="5dp"
android:padding="8dp"
android:text="DURATION">
</TextView>
<TextView
android:id="#+id/person_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:background="#drawable/bg_rounded_30"
android:drawableEnd="#drawable/ic_bottom_arrow"
android:drawablePadding="4dp"
android:padding="8dp"
android:text="MYDATE">
</TextView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/delete_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center"
android:layout_margin="4dp"
android:backgroundTint="#color/colorBackground"
android:foregroundGravity="right"
android:outlineSpotShadowColor="#color/white"
android:src="#drawable/ic_bin"
android:tint="#color/colorBlack"
app:backgroundTint="#color/white"
app:fabCustomSize="30dp"
app:layout_constraintBottom_toBottomOf="#id/material_card_layout"
app:layout_constraintStart_toStartOf="#id/material_card_layout"
app:layout_constraintTop_toBottomOf="#id/material_card_layout"
app:maxImageSize="20dp" />
</LinearLayout>
</HorizontalScrollView>
Help. I don't know why my RecyclerView does not show anything. My implementation of the adapter is right. I don't know where have I gone wrong.
Here's the Fragment class:
public class RemittanceFragment extends Fragment implements View.OnClickListener {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
#BindView(R.id.remit_cancel_view)
View remitCancelView;
#BindView(R.id.remit_checkpaid_view)
View remitCheckPaidView;
#BindView(R.id.remit_create_view)
View remitCreateView;
#BindView(R.id.remit_main_menu)
View remitMainMenuView;
#BindView(R.id.btn_cancel)
Button btnCancel;
#BindView(R.id.btn_checkpaid)
Button btnCheckPaid;
#BindView(R.id.btn_create)
Button btnCreate;
#BindView(R.id.btn_back)
TextView btnGoBack;
#BindView(R.id.btn_back2)
TextView btnGoBack2;
#BindView(R.id.remit_header_title)
TextView tvRemitHeaderTitle;
#BindView(R.id.remit_cancel_list)
RecyclerView cancelRecyclerView;
public RemittanceFragment() {
// Required empty public constructor
}
public static RemittanceFragment newInstance() {
RemittanceFragment fragment = new RemittanceFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_remit_menu, container, false);
ButterKnife.bind(this, view);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
btnCancel.setOnClickListener(this);
btnCreate.setOnClickListener(this);
btnCheckPaid.setOnClickListener(this);
btnGoBack.setOnClickListener(this);
btnGoBack2.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
remitMainMenuView.setVisibility(View.GONE);
switch (v.getId()) {
case R.id.btn_cancel:
remitCancelView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CANCEL\nREMITTANCE");
populateData();
break;
case R.id.btn_checkpaid:
remitCheckPaidView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CHECK / PAID\nREMITTANCE");
break;
case R.id.btn_create:
remitCreateView.setVisibility(View.VISIBLE);
tvRemitHeaderTitle.setText("CREATE\nREMITTANCE");
break;
case R.id.btn_back:
case R.id.btn_back2:
remitMainMenuView.setVisibility(View.VISIBLE);
remitCancelView.setVisibility(View.GONE);
remitCheckPaidView.setVisibility(View.GONE);
remitCreateView.setVisibility(View.GONE);
tvRemitHeaderTitle.setText("REMITTANCE");
break;
default:
break;
}
}
public void populateData() {
List<RemitTransaction> transactions = new ArrayList<>();
transactions = RemitTransaction.createRemitTransactionList();
RemitTransactionListAdapter adapter = new RemitTransactionListAdapter
(transactions, getActivity());
cancelRecyclerView.setAdapter(adapter);
cancelRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
public static class RemitTransaction {
private String mRefno;
private String mDate;
private String mMsisdn;
private String mAmount;
public RemitTransaction(String refno, String date, String msisdn, String amount) {
mRefno = refno;
mDate = date;
mMsisdn = msisdn;
mAmount = amount;
}
public String getmRefno() {
return mRefno;
}
public String getmDate() {
return mDate;
}
public String getmMsisdn() {
return mMsisdn;
}
public String getmAmount() {
return mAmount;
}
public static ArrayList<RemitTransaction> createRemitTransactionList() {
ArrayList<RemitTransaction> transactions = new ArrayList<>();
for (int n = 0; n < 4; n++) {
transactions.add(n, new RemitTransaction(
"REF01253123" + n,
"July " + n + ", 2016",
"0920987654" + n,
"100" + n));
}
return transactions;
}
}
public class RemitTransactionListAdapter
extends RecyclerView.Adapter<RemitTransactionListAdapter.CancelVH>{
private List<RemitTransaction> mList;
private Context mContext;
public RemitTransactionListAdapter(List<RemitTransaction> list, Context context) {
mList = list;
mContext = context;
}
private Context getContext() {
return mContext;
}
#Override
public CancelVH onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = getContext();
View v = LayoutInflater.from(context).inflate(R.layout.remit_cancel_list_item, parent, false);
return new CancelVH(v);
}
#Override
public void onBindViewHolder(CancelVH holder, int position) {
RemitTransaction transaction = mList.get(position);
holder.cancelRefno.setText(transaction.getmRefno());
holder.cancelAmount.setText(transaction.getmAmount());
holder.cancelDate.setText(transaction.getmDate());
holder.cancelMsisdn.setText(transaction.getmMsisdn());
}
#Override
public int getItemCount() {
return mList.size();
}
public class CancelVH extends RecyclerView.ViewHolder {
#BindView(R.id.remit_item_refno) TextView cancelRefno;
#BindView(R.id.remit_item_amount) TextView cancelAmount;
#BindView(R.id.remit_item_date) TextView cancelDate;
#BindView(R.id.remit_item_msisdn) TextView cancelMsisdn;
public CancelVH(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
}
And here's the layout file:
<LinearLayout 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/utility_white"
android:paddingTop="#dimen/dimen_margin_vertical_extra_large">
<android.support.v7.widget.RecyclerView
android:id="#+id/remit_cancel_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
And here's the list_item layout:
<?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">
<TextView
android:id="#+id/remit_item_refno"
style="#style/RemitListItem"
android:text="VW832191"
android:textStyle="bold"
android:layout_alignParentStart="true"/>
<TextView
android:id="#+id/remit_item_amount"
style="#style/RemitListItem"
android:text="100.00"
android:textStyle="bold"
android:layout_alignParentEnd="true"/>
<TextView
android:id="#+id/remit_item_date"
style="#style/RemitListItem"
android:text="2016-07-20"
android:layout_alignParentStart="true"
android:layout_below="#+id/remit_item_refno"/>
<TextView
android:id="#+id/remit_item_msisdn"
style="#style/RemitListItem"
android:text="09273450686"
android:layout_alignParentEnd="true"
android:layout_below="#+id/remit_item_amount"/>
</RelativeLayout>
Hope you can all help me. Thank you!
in previous versions of support library 23.2.0 wrap_content not work for RecyclerView ,and with support library 23.2.0 and above wrap_content work perfectly (now latest version is 24.0.0),
i guess that is your problem.
I want to create a custom row adapter to my Android application.
So I have build this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="5dp"
android:clickable="true"
android:orientation="vertical">
<TextView
android:id="#+id/medication"
android:textColor="#color/white"
android:textSize="16dp"
android:textStyle="bold"
android:layout_width="120dp"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/instructions"
android:textColor="#color/white"
android:layout_toRightOf="#+id/medication"
android:layout_width="170dp"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/startDate"
android:textColor="#color/white"
android:layout_width="100dp"
android:layout_toRightOf="#+id/instructions"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/active"
android:textColor="#color/white"
android:layout_width="match_parent"
android:layout_toRightOf="#+id/startDate"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Now I have build this adaptor class "MedicationAdapter.java":
public class MedicationAdapter extends RecyclerView.Adapter<MedicationAdapter.MyMedicationViewHolder> {
private List<Medication> moviesList;
public class MyMedicationViewHolder extends RecyclerView.ViewHolder {
public TextView medication, instruction, startDate,active;
public MyMedicationViewHolder(View view) {
super(view);
medication = (TextView) view.findViewById(R.id.medication);
instruction = (TextView) view.findViewById(R.id.instructions);
startDate = (TextView) view.findViewById(R.id.startDate);
active = (TextView) view.findViewById(R.id.active);
}
}
public MedicationAdapter(List<Medication> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyMedicationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.medications_list_row, parent, false);
return new MyMedicationViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyMedicationViewHolder holder, int position) {
Medication medication = moviesList.get(position);
holder.medication.setText(medication.getDrugInfo().getDisplayName());
holder.instruction.setText(medication.getFrequency()+" "+ medication.getDose());
holder.startDate.setText(medication.getDateStart());
holder.active.setText("SI");
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
Now if I try to run my Android application, I can see my activity like this:
Now I want to insert a title Text in the head of this list, and I want to insert a border line to every cell.
It is possible to do this?
regards
Yes, it's possible. You can implement header for your RecyclerView.
Pls look at this answer https://stackoverflow.com/a/26573338/1554094
You can use item decoration. There are answers on same question How to add dividers and spaces between items in RecyclerView?
Or you can just add view with height 1dp at bottom of you view item
you can try below code to set header in recyclerview
public class HeaderAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 1;
String[] data;
public HeaderAdapter(String[] data) {
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
return new VHItem(null);
} else if (viewType == TYPE_HEADER) {
//inflate your layout and pass it to view holder
return new VHHeader(null);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof VHItem) {
String dataItem = getItem(position);
//cast holder to VHItem and set data
} else if (holder instanceof VHHeader) {
//cast holder to VHHeader and set data for header.
}
}
#Override
public int getItemCount() {
return data.length + 1;
}
#Override
public int getItemViewType(int position) {
if (isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEM;
}
private boolean isPositionHeader(int position) {
return position == 0;
}
private String getItem(int position) {
return data[position - 1];
}
class VHItem extends RecyclerView.ViewHolder {
TextView title;
public VHItem(View itemView) {
super(itemView);
}
}
class VHHeader extends RecyclerView.ViewHolder {
Button button;
public VHHeader(View itemView) {
super(itemView);
}
}
}
for border in Recyclerview
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
// set the adapter
recyclerView.setAdapter(mAdapter);
public class DividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{
android.R.attr.listDivider
};
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Drawable mDivider;
private int mOrientation;
public DividerItemDecoration(Context context, int orientation) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
setOrientation(orientation);
}
public void setOrientation(int orientation) {
if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
throw new IllegalArgumentException("invalid orientation");
}
mOrientation = orientation;
}
#Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
#Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
}
}
I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.