Swipe ListItem + Pull-To-Refresh effect + Click event + Vertical scroll - java

I need a listview with vertical scroll, allowing a Pull-To-Refresh effect, and each cell must allow a Swipe (to show the button below). Furthermore, the whole ListView is contained in a three tabs activity. It's very similar to Gmail app for Android, which in inbox allows vertical scrolling, swipe to Archive conversation, and click to read the email.
The general activity contains tabs (SlidingTabLayout built with an HorizontalScrollView, SlidingTabStrip, and a ViewPager), extracted from developer.android.com.
Each tab contains a fragment with a FrameLayout, and a 47degree SwipeListView, inside. They're attached here.
We have disabled the horizontal movement of tabs (they work just clicking the header
I attach the layout of the cell and the java class which handles everything, too.
I implemented 47deg SwipeList library (https://github.com/47deg/android-swipelistview).
The errors I'm facing are: On one hand, the cell with swipe is not receiving the main click, and when I do swipe, the button bellow is shown but the click is not received correctly. And if we enable pull-to-refresh, the swipe stops working well.
layout_list_item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:id="#+id/back"
android:tag="back"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/gold">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btFavorite"
android:background="#drawable/abc_btn_rating_star_off_mtrl_alpha"
android:layout_alignParentLeft="false"
android:adjustViewBounds="true"
android:contentDescription="Favorite"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/front"
android:tag="front"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
android:layout_marginLeft="5dp">
<include android:id="#+id/layout_list_item_image" layout="#layout/layout_list_item_image"
android:layout_width="70dp"
android:layout_height = "70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<include android:id="#+id/layout_list_item_content" layout="#layout/layout_list_item_content"
android:layout_width="184dp"
android:layout_toRightOf="#id/layout_list_item_image"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
/>
<include android:id="#+id/layout_list_item_status"
layout="#layout/layout_list_item_status"
android:layout_width="match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"/>
</LinearLayout>
</FrameLayout >
layout_fragment_pager_contact_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="match_parent"
android:layout_height="match_parent"
android:clickable="false"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:clickable="false">
<com.fortysevendeg.swipelistview.SwipeListView
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#android:id/list"
android:listSelector="#00000000"
android:layout_width="match_parent"
android:layout_height="match_parent"
swipe:swipeFrontView="#+id/front"
swipe:swipeBackView="#+id/back"
swipe:swipeActionRight="reveal"
swipe:swipeMode="right"
swipe:swipeCloseAllItemsWhenMoveList="true"
swipe:swipeOpenOnLongPress="false"
swipe:swipeAnimationTime="350"
swipe:swipeOffsetLeft="280dp"
swipe:swipeOffsetRight="280dp"
/>
<!-- View to show if the list is emtpy -->
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No items."
android:clickable="false"/>
</FrameLayout>
</LinearLayout>
ContactListFragment.java
package com.davduran.myapp.contacts.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.davduran.myapp.R;
import com.davduran.myapp.contacts.connection.ContactController;
import com.davduran.myapp.contacts.detail.ContactDetailMainActivity;
import com.davduran.myapp.util.Constants;
import com.davduran.myapp.util.Utils;
import com.davduran.myapp.view.tab.SlidingTabLayout;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import io.realm.Realm;
import model.Contact;
import model.FavouriteContact;
import model.RecentContact;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class ContactListFragment extends ListFragment {
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private Realm realm;
private ContactController mContactController;
private ArrayList<Contact> contactList;
private ArrayList<FavouriteContact> favouriteContactList;
private ArrayList<RecentContact> recentContactList;
protected Handler handler = new Handler();
private ContactListViewArrayAdapter adapter;
private SwipeListView swipeListView;
private ListView listView;
private Parcelable state;
private TextView emptyText;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private int mIndex;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static ContactListFragment newInstance(int index, String param2) {
ContactListFragment fragment = new ContactListFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, index);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_fragment_pager_contact_list, container, false);
listView = (ListView) v.findViewById(android.R.id.list);
emptyText = (TextView) v.findViewById(android.R.id.empty);
return v;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ContactListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getInstance(getActivity());
mContactController = new ContactController(getActivity(),realm);
if (getArguments() != null) {
mIndex = getArguments().getInt(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setListAdapterTabs();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(Constants.TAG, "ContactListFragment.onListItemClick: Listclicking");
if (mListener != null) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
//mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).getId());
Intent in = new Intent(getActivity(), ContactDetailMainActivity.class);
if(mIndex == Constants.CONTACTS_ALL) {
in.putExtra(Constants.CONTACT_ID,contactList.get(position).getId() );
startActivity(in);
} else if (mIndex == Constants.CONTACTS_RECENT) {
try {
String action = recentContactList.get(position).getAction();
if (action.compareTo("call") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchCall(phone, getActivity());
}
}
else if (action.compareTo("sms") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchSms(phone, getActivity());
}
}
else if (action.compareTo("email") == 0) {
String strEmails = recentContactList.get(position).getEmails();
if (strEmails != null) {
JSONArray jPhones = new JSONArray(strEmails);
String email = (String)((JSONObject) jPhones.get(0)).get("email");
Utils.launchEmail(email, getActivity());
}
}
} catch (Exception ex) {
Log.e(Constants.TAG, "ContactListFragment.onListItemClick: ", ex);
}
} else if (mIndex == Constants.CONTACTS_FAVOURITE) { {
in.putExtra(Constants.CONTACT_ID,favouriteContactList.get(position).getId() );
startActivity(in);
}}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
#Override
public void onDestroyView() {
super.onDestroyView();
realm.close();
}
public void setListAdapterTabs(){
Log.i(Constants.TAG, "ContactListFragment.setListAdapterTabs: index " + mIndex);
if(mIndex == Constants.CONTACTS_FAVOURITE) {
favouriteContactList = mContactController.getAllFavouriteContacts();
if (favouriteContactList!=null) {
setListAdapter(new ContactFavouriteListViewArrayAdapter(getActivity().getApplicationContext(),
favouriteContactList));
}
}else if(mIndex == Constants.CONTACTS_RECENT){
if (emptyText!=null)
emptyText.setText("");
recentContactList = mContactController.getAllRecentContacts();
if (recentContactList!=null) {
setListAdapter(new RecentListViewArrayAdapter(getActivity().getApplicationContext(), recentContactList));
}
}else if(mIndex == Constants.CONTACTS_ALL){
if (emptyText!=null)
emptyText.setText("");
contactList = mContactController.getAllContacts();
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
if (contactList!=null) {
if (listView!=null)
state = listView.onSaveInstanceState();
if (adapter != null){
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
} else {
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
}
}
}
}
}

Related

How to fix EditText part from ListView inside fragment?

Wanna make to search with using EditText when I click it from ListView. I made it with some youtube videos or blogs. Mixed up those and of course, There's error. What should fix? I put my every codes to understand it. Need you guys help a lot.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Playbook">
<ListView
android:id="#+id/listView2"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_baseline_search_24"
android:id="#+id/searchImage" />
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_toRightOf="#id/searchImage"
android:id="#+id/editTextFilter"/>
<TextView
android:id="#+id/termName"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editTextFilter"
style="#style/TextAppearance.AppCompat.Title"
android:text="Term"/>
</RelativeLayout>
This is layout part.
package com.example.gridiron;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Use the {#link Playbook#newInstance} factory method to
* create an instance of this fragment.
*/
public class Playbook extends Fragment {
ArrayList<PlaybookList> arrayList2;
ListView listView2;
private static PlaybookListAdapter playbookListAdapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Playbook() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Playbook.
*/
// TODO: Rename and change types and number of parameters
public static Playbook newInstance(String param1, String param2) {
Playbook fragment = new Playbook();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_playbook, container, false);
ListView listView2 = (ListView) view.findViewById(R.id.listView2);
EditText editTextFilter = (EditText) view.findViewById(R.id.editTextFilter);
ArrayList<PlaybookList> arrayList2 = new ArrayList<>();
arrayList2.add(new PlaybookList("Quarterback", "https://namu.wiki/w/%EC%BF%BC%ED%84%B0%EB%B0%B1"));
arrayList2.add(new PlaybookList("Runningback", "https://namu.wiki/w/%EB%9F%AC%EB%8B%9D%EB%B0%B1"));
PlaybookListAdapter playbookListAdapter = new PlaybookListAdapter(getActivity(), R.layout.list_row2, arrayList2);
listView2.setAdapter(playbookListAdapter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable edit) {
String filterText = edit.toString();
if (filterText.length() > 0) {
listView2.setFilterText(filterText);
} else {
listView2.clearTextFilter();
}
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.valueOf(arrayList2.get(position).getTermURL())));
getActivity().startActivity(intent);
}
});
return view;
}
}
package com.example.gridiron;
public class PlaybookList {
String TermName;
String TermURL;
public PlaybookList(String termName, String termURL) {
TermName = termName;
TermURL = termURL;
}
public String getTermName() {
return TermName;
}
public void setTermName(String termName) {
TermName = termName;
}
public String getTermURL() {
return TermURL;
}
public void setTermURL(String termURL) {
TermURL = termURL;
}
}
package com.example.gridiron;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class PlaybookListAdapter extends ArrayAdapter<PlaybookList> {
private Context mContext;
private int mResource;
public PlaybookListAdapter(#NonNull Context context, int resource, #NonNull ArrayList<PlaybookList> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
TextView termName = convertView.findViewById(R.id.termName);
termName.setText(getItem(position).getTermName());
return convertView;
}
}
And last 3 codes are for class. It's really hard to make it. Please, Help me!
There is no ListView in your layout code. You didn't include the error but I'm pretty sure it's NullPointerException on this line:
listView2.setAdapter(playbookListAdapter);

How to programmatically Next and Prev buttons for Master / Detail flow

I have created a sample app using the "Master / Detail flow" activity. I have added two buttons, Next and Prev to the detail activity. How to I set programmatically the buttons actions instead having to go back and forth between the List and detail?
item_detail.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="30dp"
android:paddingEnd="30dp"
android:weightSum="4"
android:gravity="end"
android:orientation="horizontal">
<Button
android:id="#+id/button_prev"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Prev"/>
<Button
android:id="#+id/button_next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next"/>
</LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textIsSelectable="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailFragment"/>
</LinearLayout>
activity_item_detail.xml
<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="co.test.app.sample.itemapplication.ItemDetailActivity"
tools:ignore="MergeRootFrame">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/detail_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
DummyContent.java
package co.test.app.sample.itemapplication.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p>
* TODO: Replace all uses of this class before publishing your app.
*/
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
}
private static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
private static DummyItem createDummyItem(int position) {
return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
}
private static String makeDetails(int position) {
StringBuilder builder = new StringBuilder();
builder.append("Details about Item: ").append(position);
for (int i = 0; i < position; i++) {
builder.append("\nMore details information here.");
}
return builder.toString();
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public DummyItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
#Override
public String toString() {
return content;
}
}
}
ItemDetailActivity.java
package co.test.app.sample.itemapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
/**
* An activity representing a single Item detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link ItemListActivity}.
*/
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
ItemListActivity.java
package co.test.app.sample.itemapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import co.test.app.sample.itemapplication.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of Items. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link ItemDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class ItemListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
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();
}
});
View recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
This is the code snippet used to forward to the detail page.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
You can forward to any page by changing the value of arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
Use the above snippets in the onClick events of next and prev buttons. cheers :)

Scrollview is not working in fragment

<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="wrap_content"
android:orientation="vertical"
tools:context="mcb.myclickbazaar.Fragments.DateTimePlace">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:isScrollContainer="false"
android:fillViewport="true"
android:padding="10dp">
<LinearLayout>
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
<LinearLayout...>
</LinearLayout>
</ScrollView>
</RelativeLayout>
The scrollview is not working. I have tried all the answers from stackoverflow, but still can't find a way to solve this issue.
This xml file is a fragment. It is one of the fragment from tabbedView Activity.
EDIT
JAVA FILE
package mcb.myclickbazaar.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import mcb.myclickbazaar.Fragments.DateTimePlace;
import mcb.myclickbazaar.Fragments.FinalBill;
import mcb.myclickbazaar.Fragments.ItemSelect;
import mcb.myclickbazaar.R;
public class ProceedingsActivity extends AppCompatActivity implements ItemSelect.OnFragmentInteractionListener,
DateTimePlace.OnFragmentInteractionListener,FinalBill.OnFragmentInteractionListener{
private static final String TAG = "ProceedingsActivity";
private ViewPager mViewPager;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proceedings);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
viewPager = (ViewPager) findViewById(R.id.viewpager_proceedings);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#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_proceedings, 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 void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new ItemSelect(), "Select");
adapter.addFragment(new DateTimePlace(), "DateTime");
adapter.addFragment(new FinalBill(), "Bill");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentInteraction(Uri uri) {
Log.e(TAG,"Working: on onFragmentInteraction");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment Code
package mcb.myclickbazaar.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import mcb.myclickbazaar.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link DateTimePlace.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link DateTimePlace#newInstance} factory method to
* create an instance of this fragment.
*/
public class DateTimePlace extends Fragment implements AdapterView.OnItemSelectedListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private String upcoming_date_1,upcoming_date_2,upcoming_date_3,upcoming_date_4;
private EditText editText_date;
private EditText editText_time;
private Spinner spinner_calendar;
private Spinner spinner_time;
private OnFragmentInteractionListener mListener;
public DateTimePlace() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment DateTimePlace.
*/
// TODO: Rename and change types and number of parameters
public static DateTimePlace newInstance(String param1, String param2) {
DateTimePlace fragment = new DateTimePlace();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// Spinner element
final View view = inflater.inflate(R.layout.fragment_date_time_place, container, false);
spinner_calendar = (Spinner) view.findViewById(R.id.spinner_calender);
spinner_time = (Spinner) view.findViewById(R.id.spinner_time);
editText_date = (EditText) view.findViewById(R.id.editText_SelectDate_DTP);
editText_time = (EditText) view.findViewById(R.id.editText_SelectTime_DTP);
editText_date.setFocusable(false);
editText_time.setFocusable(false);
editText_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_calendar.setVisibility(View.VISIBLE);
spinner_calendar.performClick();
editText_date.setHint("");
}
});
editText_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner_time.setVisibility(View.VISIBLE);
spinner_time.performClick();
editText_time.setHint("");
}
});
// Spinner click listener
spinner_calendar.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_calender = new ArrayList<String>();
categories_calender.add("Today");
categories_calender.add("Tomorrow");
categories_calender.add(getUpcoming_Date(2));
categories_calender.add(getUpcoming_Date(3));
categories_calender.add(getUpcoming_Date(4));
categories_calender.add(getUpcoming_Date(5));
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_calendar = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_calender);
// Drop down layout style - list view with radio button
dataAdapter_calendar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_calendar.setAdapter(dataAdapter_calendar);
// Spinner click listener
spinner_time.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories_time = new ArrayList<String>();
categories_time.add("9AM - 11AM");
categories_time.add("11AM - 1PM");
categories_time.add("1PM - 3PM");
categories_time.add("3PM - 5PM");
categories_time.add("5PM - 7PM");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter_time = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, categories_time);
// Drop down layout style - list view with radio button
dataAdapter_time.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner_time.setAdapter(dataAdapter_time);
return view;
}
private String getUpcoming_Date(int upcoming){
Calendar c = Calendar.getInstance();
Date dt = new Date();
c.add(Calendar.DATE, upcoming);
SimpleDateFormat df = new SimpleDateFormat("EEE,dd MMM", Locale.US);
String formattedDate = df.format(c.getTime());
return formattedDate;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
try this :
make hight match_parent for relativeLayout and ScrollView both like below
<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:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sdsd"/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Keep scroll view height as match parent and the height of everything inside it as wrap content.

Getting text from Textview in listview with custom adapter [duplicate]

This question already has answers here:
How to extract the text from the selected item on the listView
(14 answers)
Listview with Details
(4 answers)
Closed 7 years ago.
I have a Listview with 3 Textviews, and I want to retrieve the specific data from these textviews on the clicked Item. For now I'm trying to get the data from the first textview. The problem is, it doesn't matter if I click on Item 1, 2, 3 or etc because I'll always get the text from first Item on the listview. I think the problem is because I don't know how to specific which data I want, from which Item. This is my code:
estoque.java:
package com.example.asus.mingausfashionmoda;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class estoque extends ListActivity {
String qntES;
String pcES;
String pvES;
//list
protected List<ParseObject> mObject;
String variable = "camisa";
// declare class variables
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.estoque_main);
// instantiate our ItemAdapter class
m_adapter = new ItemAdapter(this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
// here we are defining our runnable thread.
viewParts = new Runnable(){
public void run(){
handler.sendEmptyMessage(0);
}
};
// here we call the thread we just defined - it is sent to the handler below.
Thread thread = new Thread(null, viewParts, "MagentoBackground");
thread.start();
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
// create some objects
// here is where you could also request data from a server
// and then create objects from that data.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(variable);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> statuslist, ParseException e) {
if(e != null){
//data successfully retrieved
Toast.makeText(estoque.this, "Houve um erro inesperado, tente novamente mais tarde", Toast.LENGTH_LONG).show();
}else{
//something went wrong
mObject = statuslist;
for(int i = 0; i<mObject.size(); i++) {
ParseObject statusObject = mObject.get(i);
String username = statusObject.getString("user");
Number qntE = statusObject.getNumber("qnt");
qntES = String.valueOf(qntE);
Number pcE = statusObject.getNumber("precoC");
pcES = String.valueOf(pcE);
Number pvE = statusObject.getNumber("precoV");
pvES = String.valueOf(pvE);
m_parts.add(new Item(qntES, pvES, pcES));
m_adapter = new ItemAdapter(estoque.this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
}
}
}
});
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
}
};
}
ItemAdapter.java:
package com.example.asus.mingausfashionmoda;
/**
* Created by ASUS on 21/12/2015.
*/
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ItemAdapter extends ArrayAdapter<Item> {
// declaring our ArrayList of items
private ArrayList<Item> objects;
/* here we must override the constructor for ArrayAdapter
* the only variable we care about now is ArrayList<Item> objects,
* because it is the list of objects we want to display.
*/
public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(int position, View convertView, ViewGroup parent){
// assign the view we are converting to a local variable
View v = convertView;
/** v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CARALHO VC CRICOU" + objects);
}
}); */
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
/*
* Recall that the variable position is sent in as an argument to this method.
* The variable simply refers to the position of the current object in the list. (The ArrayAdapter
* iterates through the list we sent it)
*
* Therefore, i refers to the current Item object.
*/
Item i = objects.get(position);
if (i != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView btd = (TextView) v.findViewById(R.id.desctext);
// check to see if each individual textview is null.
// if not, assign some text!
if (tt != null){
tt.setText("Quantidade: ");
}
if (ttd != null){
ttd.setText(i.getName());
}
if (mt != null){
mt.setText("Preco compra: ");
}
if (mtd != null){
mtd.setText("$" + i.getPrice());
}
if (bt != null){
bt.setText("Preco venda: ");
}
if (btd != null){
btd.setText(i.getDetails());
}
}
// the view must be returned to our activity
return v;
}
}
Item.java:
package com.example.asus.mingausfashionmoda;
import android.widget.TextView;
public class Item {
private String details;
private String name;
private String price;
public Item(){
}
public Item(String i, String d, String p){
this.details = d;
this.name = i;
this.price = p;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
estoque_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnSelecionarQuery"
android:text="ROUPA"
/>
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No items to display."/>
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<!-- Item Name -->
<TextView
android:id="#+id/toptext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Actual Item Name Data -->
<TextView
android:id="#+id/toptextdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/toptext"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Price Tag -->
<TextView
android:id="#+id/middletext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentLeft="true"
android:layout_below="#id/toptext"
android:textStyle="bold"
android:gravity="center_vertical"
/>
<!-- Actual Price Data -->
<TextView
android:id="#+id/middletextdata"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentRight="true"
android:layout_below="#id/toptext"
android:layout_toRightOf="#id/middletext"
android:gravity="center_vertical"
/>
<!-- Description Tag -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/middletext"
android:textStyle="bold"
android:id="#+id/bottomtext"
android:singleLine="false"
/>
<!-- This is the actual description -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/bottomtext"
android:id="#+id/desctext"
android:singleLine="false"
/>
</RelativeLayout>
To make it easier for your understanding, this is where I get the clicked item from the listview and try to get it's first textview text(This is on estoque.java):
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
Thanks.
Want to access View from clicked row layout of ListView, use second parameter of onItemClick to call findViewById like:
TextView ttd = (TextView) myView.findViewById(R.id.toptextdata);
Make your textView final and instead of using listItemClickListner use onclickListener on each textview in the getView().

Android: How to set the ImageView src in a list dynamically

I'm new to android, i have a news website
and i'm developing an android app, the main activity catches a JSON node from this link and displays all the articles in a ListView,
each item in the list has an image, title and a teaser of this particular article.
now i have written a java code for the title and the description and everything is working perfectly, but i want to display the images too and i don't know how to do that.
Here's my MainActivity.java:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
//Create a progress dialog instance
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.ana.fm/api/main/";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_TEASER = "teaser";
private static final String TAG_COVER_PHOTO = "cover_photo";
// contacts JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String article_id = ((TextView) view.findViewById(R.id.article_id))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID, article_id);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All Contacts
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
title = Html.fromHtml(title).toString();
String teaser = c.getString(TAG_TEASER);
teaser = Html.fromHtml(teaser).toString();
String cover_photo = "http://www.ana.fm/med_photos/articles/";
cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));
// tmp hashmap for single contact
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_TEASER, teaser);
article.put(TAG_COVER_PHOTO, cover_photo);
// adding contact to contact list
contactList.add(article);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
new GetContacts().execute();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_TITLE, TAG_TEASER, TAG_COVER_PHOTO}, new int[] { R.id.article_id, R.id.title,
R.id.teaser, R.id.cover_photo});
setListAdapter(adapter);
}
}
}
And here's the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/white">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
/>
</LinearLayout>
And here's the list_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"
android:orientation="vertical"
android:padding="10dp"
android:layout_marginBottom="20dp"
android:background="#color/light_grey">
<!-- Cover photo -->
<ImageView
android:id="#+id/cover_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<!-- ID Label -->
<TextView
android:id="#+id/article_id"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
<!-- Title Label -->
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:paddingTop="6dip"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- Teaser label -->
<TextView
android:id="#+id/teaser"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/medium_grey" />
</LinearLayout>
Anyone can help ?
So here is how to implement a custom adapter.
For this example we have a person object containing properties for name, surname and imageUrl (the web location for the image)
The following is the Person Class Object:
public class Person {
String name;
String surname;
String imageUrl;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
Now we create an xml layout which will populate our listview with data. Nothing fancy here just a layout containing a textview for name, another for surname and an imageview for our image. The file in this case is called person_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/person_cell_txtName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/person_cell_txtSurname" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/person_cell_imageview" />
</LinearLayout>
So til now we have a class for our person object, and an xml layout ready for use. Now we build our Custom Adapter. Create a class named MyAdapter which extends ArrayAdapter of type Person. Note that we need to pass the context to the adapter since we will be using Picasso to load the image.
public class MyAdapter extends ArrayAdapter<Person> {
Context context;
List<Person>myList;
public MyAdapter(Context context, int resource, List<Person> objects) {
super(context, resource, objects);
this.context = context;
this.myList = objects;
}
#Override
public int getCount() {
if(myList != null)
return myList.size();
return 0;
}
#Override
public Person getItem(int position) {
if(myList != null)
return myList.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(myList != null)
return myList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
//If the listview does not have an xml layout ready set the layout
if (convertView == null){
//we need a new holder to hold the structure of the cell
holder = new Holder();
//get the XML inflation service
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate our xml cell to the convertView
convertView = inflater.inflate(R.layout.person_cell, null);
//Get xml components into our holder class
holder.txtName = (TextView)convertView.findViewById(R.id.person_cell_txtName);
holder.txtSurname = (TextView)convertView.findViewById(R.id.person_cell_txtSurname);
holder.imageView = (ImageView)convertView.findViewById(R.id.person_cell_imageview);
//Attach our holder class to this particular cell
convertView.setTag(holder);
}else{
//The listview cell is not empty and contains already components loaded, get the tagged holder
holder = (Holder)convertView.getTag();
}
//Fill our cell with data
//get our person object from the list we passed to the adapter
Person person = getItem(position);
//Fill our view components with data
holder.txtName.setText(person.getName());
holder.txtSurname.setText(person.getSurname());
Picasso.with(context).load(person.getImageUrl()).fit().into(holder.imageView);
return convertView;
}
/**
* This holder must replicate the components in the person_cell.xml
* We have a textview for the name and the surname and an imageview for the picture
*/
private class Holder{
TextView txtName;
TextView txtSurname;
ImageView imageView;
}
}
Then in our Activity we can simply populate our List of person objects and create an instance of our adapter and set it as the listview main adapter.
ListView myListView = new ListView(getApplicationContext());
List<Person> personList = new ArrayList<>();
Person person = new Person();
person.setName("John");
person.setSurname("Doe");
person.setImageUrl("https://lh3.googleusercontent.com/-Sa9kdnhuE5E/AAAAAAAAAAI/AAAAAAAAABs/ILmJ8_sk9aY/photo.jpg");
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.person_cell, personList);
myListView.setAdapter(adapter);
This is basically the story behind a custom adapter.
Based on your JSON,all you have is the image file name. ie:
{
.
.
.
"cover_photo":"2018061675.jpg"
}
You will first need an API to deliver the InputStream from your image.
after that you have 3 options:
Volley
Its a very simple to use(but very powerful) library which takes care of maintaining your resource pool and memory when you.
This video is an introduction to volley.Please watch it if you have prior android experience or I would suggest watching to merely understand how it affects your normal methods.
making an image request is mentioned in the android tutorial for volley
OkHttp
It requires more working and is lightweight for overall http request use.
the image request can be obtained as file as detailed here
Picasso
Simple library meant solely for image request purposes
Do it manually
Use an input stream and fetch and build your image manually
This is is a good example or that.

Categories

Resources