ListView setOnItemClickListener is not fired / called - java

I know this question is asked several times here, and i go through all the answer and tried implementing it in my code, but the result is fail. That's why i have posted a new question to get my code run. Question is simple whenever i want to trigger listView.setOnItemClickListener(this). It is not fired. I tried each suggestion given in stackoverflow but not able to solve the issue.
Code i used are
visitor_list_fragment.xml file
<?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:id="#+id/node_name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:textIsSelectable="false"
android:textSize="20sp" />
<ListView
android:id="#+id/visitor_list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:cacheColorHint="#00000000"
android:dividerHeight="5dp"
android:listSelector="#00000000"
android:scrollingCache="true"
android:smoothScrollbar="true" >
</ListView>
</LinearLayout>
visitor_list_item.xml file
<?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:background="#android:color/transparent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/photo_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:contentDescription="#string/image_name"
android:focusable="false" />
<TextView
android:id="#+id/profile_info_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:focusable="false"
android:textColor="#android:color/black"
android:textIsSelectable="false"
android:textSize="20sp" />
</LinearLayout>
Code where i called onItemClickListener
public class VisitorListFragment extends Fragment implements OnItemClickListener
{
private TextView m_NodeName;
private ListView m_VisitorListView;
private VisitorListAdapter m_VisitorNodeListAdapter = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.visitor_list_fragment, null);
m_NodeName = (TextView)view.findViewById(R.id.node_name_textView);
m_VisitorNodeListAdapter = new VisitorListAdapter(getActivity().getApplicationContext());
m_VisitorListView = (ListView)view.findViewById(R.id.visitor_list_view);
// Displaying header & footer in the list-view
TextView header = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
header.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addHeaderView(header, null, false);
TextView footer = (TextView) getActivity().getLayoutInflater().inflate(R.layout.list_headfoot, null);
footer.setBackgroundResource(R.drawable.header_footer_img);
m_VisitorListView.addFooterView(footer, null, false);
m_VisitorListView.setAdapter(m_VisitorNodeListAdapter);
m_VisitorListView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String nodeName = m_VisitorNodeListAdapter.getNodeName(position);
System.out.println(nodeName);
}
}
AdapterClass
public class VisitorListAdapter extends BaseAdapter
{
private HashMap<String, String> m_ProfileImagePath;
private HashMap<String, String> m_ProfileInfo;
private ArrayList<String> m_NodeName;
private LayoutInflater m_Inflater=null;
public VisitorListAdapter(Context context)
{
super();
m_ProfileImagePath = new HashMap<String, String>();
m_ProfileInfo = new HashMap<String, String>();
m_NodeName = new ArrayList<String>();
m_Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getItem(int arg0)
{
return null;
}
public int getCount()
{
return m_NodeName.size();
}
public long getItemId(int position)
{
return position;
}
public boolean isEnabled(int position)
{
return false;
}
public String getNodeName(int position)
{
return m_NodeName.get(position);
}
public class ViewHolder
{
TextView profileInfoTextView;
ImageView profileImageView;
}
public void addProfileInfo(String nodeName, String profileInfo)
{
boolean found = false;
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
found = true;
}
}
if(found == false)
{
m_NodeName.add(nodeName);
m_ProfileInfo.put(nodeName, profileInfo);
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
}
public void addProfileImagePath(String nodeName, String profileInfoImagePath)
{
m_ProfileImagePath.put(nodeName, Utilities.CHORD_FILE_PATH + "/" + profileInfoImagePath);
notifyDataSetChanged();
}
public void removeNode(String nodeName)
{
for(int i = 0; i<m_NodeName.size(); i++)
{
if(nodeName.equals(m_NodeName.get(i)))
{
m_NodeName.remove(i);
m_ProfileInfo.remove(nodeName);
m_ProfileImagePath.remove(nodeName);
}
}
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public void clearAll()
{
m_ProfileImagePath.clear();
m_NodeName.clear();
m_ProfileInfo.clear();
notifyDataSetChanged();
ChordActvityManager.getSingletonObject().setNodeNameList(m_NodeName);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = m_Inflater.inflate(R.layout.visitor_list_item, null);
holder.profileImageView = (ImageView)convertView.findViewById(R.id.photo_view);
holder.profileInfoTextView = (TextView)convertView.findViewById(R.id.profile_info_textview);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
// Put the code in an async task
new ImageLoaderTask(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return convertView;
}
class ImageLoaderTask extends AsyncTask<URL, Integer, Long>
{
private int position;
private ViewHolder holder;
ImageLoaderTask(int position, ViewHolder holder)
{
this.position = position;
this.holder = holder;
}
#Override
protected void onPreExecute()
{
String loadPath = m_ProfileImagePath.get(m_NodeName.get(position));
Bitmap bitmap = BitmapFactory.decodeFile(loadPath);
if(bitmap != null)
{
holder.profileImageView.setImageBitmap(bitmap);
}
holder.profileInfoTextView.setText(m_ProfileInfo.get(m_NodeName.get(position)));
}
#Override
protected Long doInBackground(URL... urls)
{
return null;
}
#Override
protected void onProgressUpdate(Integer... progress)
{
}
#Override
protected void onPostExecute(Long result)
{
}
}
}

public boolean isEnabled(int position)
{
return false;
}
This should be true for all active elements!

Try removing
android:focusable="false" and
android:textIsSelectable="false"
from listView_item.xml file...

Check if your m_VisitorListView isn't null (debugging mode).
Check the import onItemClick, should be AdapterView.OnItemClickListener
If you still facing this issue try implementing it anonymously:
m_VisitorListView .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
} );

Related

payload shows correct data but dors not update arraylist

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>

Fragment GridView first item not being displayed despite setting properties

After creating a gridview within a scrollview, the view itself appears as normal but the first value does not apper at all. I've tried looking at similar questions but I still don't understand what has gone wrong. What needs to change in order to fix this problem?
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/History_textView0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#android:color/white"
android:text="Years"
style="#android:style/TextAppearance.Medium" />
<com.ages.events.GridViewHistory
android:id="#+id/History_GridView0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:layout_marginBottom="20dp"
android:stretchMode="columnWidth"
android:layout_below="#+id/History_textView0"/>
<TextView
android:id="#+id/History_textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#android:color/white"
android:text="Events"
style="#android:style/TextAppearance.Medium"
android:layout_below="#+id/History_GridView0" />
</RelativeLayout>
java
public class TabFragmentHistory extends android.support.v4.app.Fragment {
static final String[] years = new String[]{
"1863", "1864", "1868", "1871", "1890", "1898", "1900", "1906", "1968", "1979"
};
GridView mGridView0;
public MyAdapter adapter;
public TabFragmentHistory() {
// Required empty constructor
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_history, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
mGridView0 = (GridView) v.findViewById(R.id.HistoryGridView0);
adapter = new MyAdapter(getActivity().getApplicationContext(), 0);
mGridView0.setAdapter(adapter);
for (int i = 1; i < years.length; i++) {
adapter.addAdapterItem(new AdapterItem(years[i]));
}
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends ArrayAdapter< AdapterItem > {
private List< AdapterItem > items = new ArrayList< AdapterItem >();
// private static LayoutInflater inflater = null;
public MyAdapter(Context context, int textviewid) {
super(context, textviewid);
}
public void addAdapterItem(AdapterItem item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
#Override
public AdapterItem getItem(int position) {
return ((null != items) ? items.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressWarnings("deprecation")
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
View rowView;
if (convertView == null) {
rowView = getActivity().getLayoutInflater().inflate(R.layout.gridview_item, parent, false);
} else {
rowView = convertView;
}
TextView tv = (TextView) rowView.findViewById(R.id.item_gridview);
tv.setText(items.get(position).first);
return rowView;
}
}
public class AdapterItem {
public String first;
// add more items
public AdapterItem(String first) {
this.first = first;
}
}
}
for (int i = 1; i < years.length; i++) {
adapter.addAdapterItem(new AdapterItem(years[i]));
}
Should this be starting at i = 0?

Android: calling getview() for ListView's Adapter from Fragment in viewPager

I have ViewPager that containing 3 different Fragment. each Fragment containing A Different View and also ListView, I got a problem when I was trying to show the ListView in one of Fragment from ViewPager, it doesn't show anything. I've tried to debug my adapter and it seems my getView() method is not called. I try to call my Fragment not from ViewPager, the result is getView() is called from adapter and ListView is showing. Is there any problem to show ListView from ViewPager? I have tried this solution by calling my adapter from onViewCreated() but there's nothing change. so is there any wrong with my method? this is my code :
My Fragment Class for Managing ViewPager
public class Frag_Provider extends Fragment {
private String[] tabsTitles = {"TERDEKAT", "SEMUA", "PROVIDERKU"};
String url = "";
List<ModelProvider> list_provider;
DB_Esehat db_esehat = null;
SQLiteDatabase db = null;
ContentLoadingProgressBar progressbar;
TabLayout tabLayout;
ViewPager pager;
public Frag_Provider (){
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).custom_toolbar("Provider", R.color.toolbar_provider, R.color.toolbar_provider_dark);
View result=inflater.inflate(R.layout.fragment_provider, container, false);
list_provider = new ArrayList<ModelProvider>();
progressbar = (ContentLoadingProgressBar)result.findViewById(R.id.progressbar);
db_esehat = new DB_Esehat(getActivity());
db = db_esehat.getWritableDatabase();
db.delete("LST_PROVIDER", null, null);
pager=(ViewPager)result.findViewById(R.id.pager);
tabLayout = (TabLayout)result.findViewById(R.id.sliding_tabs);
url = getResources().getString(R.string.url_host)+getResources().getString(R.string.url_provider);
new ProviderTask(url).execute();
pager.setAdapter(buildAdapter(tabsTitles));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(pager);
}
});
return(result);
}
public class ProviderTask extends AsyncTask<String, Void, String> {
String url = "";
public ProviderTask(String url) {
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
String result = "";
try {
result = Connection.get(url);
} catch (Exception e) {
result = "";
}
return result;
}
#Override
protected void onPostExecute(String result) {
progressbar.setVisibility(View.GONE);
pager.setVisibility(View.VISIBLE);
tabLayout.setVisibility(View.VISIBLE);
super.onPostExecute(result);
if (result.equals("") || result.equals(null)) {
MethodSupport.AlertDialog(getActivity());
} else {
try {
JSONArray Data = new JSONArray(result);
for (int i = 0; i < Data.length(); i++) {
String LSKA_NOTE = "";
String RSALAMAT = "";
String RSTELEPON = "";
String RSNAMA = "";
String MAPPOS = "";
int RSTYPE = 0;
int RSID = 0;
int RS_NTT = 0;
JSONObject json = Data.getJSONObject(i);
if (json.has("LSKA_NOTE")) {
LSKA_NOTE = json.getString("LSKA_NOTE");
}
if (json.has("RSALAMAT")) {
RSALAMAT = json.getString("RSALAMAT");
}
if (json.has("RSTELEPON")) {
RSTELEPON = json.getString("RSTELEPON");
}
if (json.has("RSNAMA")) {
RSNAMA = json.getString("RSNAMA");
}
if (json.has("MAPPOS")) {
MAPPOS = json.getString("MAPPOS");
}
if (json.has("RSTYPE")) {
RSTYPE = json.getInt("RSTYPE");
}
if (json.has("RSID")) {
RSID = json.getInt("RSID");
}
if (json.has("RS_NTT")) {
RS_NTT = json.getInt("RS_NTT");
}
db_esehat.InsertRS(LSKA_NOTE, RSALAMAT, RSTELEPON, RSNAMA, MAPPOS, RSTYPE, RSID, RS_NTT);
}
} catch (Exception e) {
Log.d("TES", e.getMessage());
}
}
}
}
private PagerAdapter buildAdapter(String[] tabsTitles) {
return(new FragmentStatePagerAdapter(getActivity(), getChildFragmentManager(),tabsTitles));
}
}
This is FragmentStatePagerAdapter.java
public class FragmentStatePagerAdapter extends FragmentPagerAdapter {
Context ctxt=null;
private String[] tabsTitles;
public FragmentStatePagerAdapter(Context ctxt, FragmentManager mgr, String[] tabsTitles) {
super(mgr);
this.ctxt=ctxt;
this.tabsTitles = tabsTitles;
}
#Override
public int getCount() {
return tabsTitles.length;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return Frag_Provider_Terdekat.newInstance(position);
case 1:
return Frag_Provider_Semua.newInstance(position);
case 2:
return Frag_Provider_Ku.newInstance(position);
}
return null;
}
// #Override public float getPageWidth(int position) { return(0.7f); }
#Override
public String getPageTitle(int position) {
return tabsTitles[position];
}
}
this is my Fragment_Provider.xml, Layout for managing my ViewPager
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</RelativeLayout>
This is of my Fragment in ViewPagerthat containing ListView :
public class Frag_Provider_Terdekat extends Fragment {
private static final String KEY_POSITION="position";
private ListView list_provider;
List<ModelProviderTerdekat> list_ekamedicare;
DB_Esehat db_esehat;
SQLiteDatabase db;
ProviderTerdekatAdapter adapter;
static Frag_Provider_Terdekat newInstance(int position) {
Frag_Provider_Terdekat frag=new Frag_Provider_Terdekat();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
return("PROVIDER KU");
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.fragment_child_providerterdekat, container, false);
list_provider = (ListView)result.findViewById(R.id.list_provider);
list_ekamedicare = new ArrayList<ModelProviderTerdekat>();
db_esehat = new DB_Esehat(getActivity());
list_ekamedicare = db_esehat.getProvider();
adapter = new ProviderTerdekatAdapter(getActivity().getApplicationContext(), R.layout.adapter_provider, list_ekamedicare);
list_provider.setAdapter(adapter);
return result;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
and this is Adapter for my ListView
public class ProviderTerdekatAdapter extends ArrayAdapter<ModelProviderTerdekat> {
List<ModelProviderTerdekat> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
static class ViewHolder {
ImageView imvprov_map;
ImageView imvprov_fav;
TextView textprov_nama_rs;
TextView textprov_alamat_rs;
TextView textprov_km_rs;
}
public ProviderTerdekatAdapter (Context context, int viewResourceId, List<ModelProviderTerdekat> data) {
super(context, R.layout.adapter_provider, data);
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflater.inflate(R.layout.adapter_provider, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.imvprov_map = (ImageView) view.findViewById(R.id.imvprov_map);
viewHolder.imvprov_fav = (ImageView) view.findViewById(R.id.imvprov_fav);
viewHolder.textprov_nama_rs = (TextView) view.findViewById(R.id.textprov_nama_rs);
viewHolder.textprov_alamat_rs = (TextView) view.findViewById(R.id.textprov_alamat_rs);
viewHolder.textprov_km_rs = (TextView) view.findViewById(R.id.textprov_km_rs);
view.setTag(viewHolder);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.textprov_nama_rs.setText(data.get(position).getRSNAMA());
viewHolder.textprov_alamat_rs.setText(data.get(position).getRSALAMAT());
return view;
}
}
I have no Idea why my GetView() not called in my Adapter, is it because I put in ViewPager? well I hope someone understand about it and help me to solver my problem. thank you very much.
Finally.. I found a solution for my problem, it's because I put ViewPager in RelativeLayout after I change into LinearLayout all view displayed as I wanted
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.widget.ContentLoadingProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"
android:indeterminate="false" />
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
app:tabMode="fixed"
android:fillViewport="true"
android:visibility="gone" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_below="#id/sliding_tabs"
android:visibility="gone"/>
</LinearLayout>

Unable to listen to setOnItemClickListener in ListView - Android

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.

Custom ArrayAdapter showing a blank screen in my Fragment

So I've just been messing around with android for a little bit and I've run into a bit of a snag. The fragment where I am instantiating ListOfJokesTypesAdapter for some reason is not displaying a listview populated with the Data from my JokeData class.
All that I get is a blank screen (no errors or anything of that nature).
This is just a proof of concept thing I've been working on so any help would be greatly appreciated. Why is it that this particular custom adapter is not working while my MainClassAdapter is working just fine.
The Code
My Joke Class:
public class Joke {
private String jokeSetup;
private String jokePunchline;
public Joke(String jokeSetup, String jokePunchline) {
this.jokeSetup = jokeSetup;
this.jokePunchline = jokePunchline;
}
public String getJokeSetup() {
return jokeSetup;
}
public void setJokeSetup(String jokeSetup) {
this.jokeSetup = jokeSetup;
}
public String getJokePunchline() {
return jokePunchline;
}
public void setJokePunchline(String jokePunchline) {
this.jokePunchline = jokePunchline;
}
}
My JokeListClass
public class JokeListData {
private String listName;
private List<Joke> arrayListOfJokes;
public JokeListData(String listName, List<Joke> arrayListOfJokes) {
this.listName = listName;
this.arrayListOfJokes = arrayListOfJokes;
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
public List<Joke> getArrayListOfJokes() {
return arrayListOfJokes;
}
public void setArrayListOfJokes(ArrayList<Joke> arrayListOfJokes) {
this.arrayListOfJokes = arrayListOfJokes;
}
}
My Actual Joke Data
public class JokeData {
private static List<Joke> dogJokes = new ArrayList<Joke>(){
{
add(new Joke("Dogs", "Bark"));
add(new Joke("Dogs", "Woof"));
add(new Joke("Dogs", "Howl"));
add(new Joke("Dogs", "Sniff"));
}
};
private static List<Joke> catJokes = new ArrayList<Joke> (){
{
add(new Joke("Cats", "woof"));
add(new Joke("Dogs", "Meow"));
}
};
static List<JokeListData> dataOfJokeList = new ArrayList<JokeListData>();
public static void addEntries(){
dataOfJokeList.add(new JokeListData("Cat Jokes", catJokes));
dataOfJokeList.add(new JokeListData("Dog Jokes", dogJokes));
}
}
The Adapter
public class ListOfJokeTypesAdapter extends ArrayAdapter<JokeListData> {
Context mContext;
int mLayoutId;
List<JokeListData> mList;
public ListOfJokeTypesAdapter(Context context, int resource, List<JokeListData> objects) {
super(context, resource, objects);
this.mContext = context;
this.mLayoutId = resource;
this.mList = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mLayoutId,parent,false);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.rowForMainList);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
return convertView;
}
private static class ViewHolder{
TextView mTextView;
}
}
The Fragment which utilizes the adapter
public class ListOfJokeTypesFragment extends Fragment {
ListView mListView;
ListOfJokeTypesAdapter listOfJokeTypesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.joke_type_fragment,container,false);
JokeData.addEntries();
mListView = (ListView)view.findViewById(R.id.jokeTypeListView);
listOfJokeTypesAdapter = new ListOfJokeTypesAdapter(getActivity().getApplicationContext(),R.layout.row,JokeData.dataOfJokeList);
mListView.setAdapter(listOfJokeTypesAdapter);
return view;
}
}
The Fragment Manager
package com.example.taranveer.jokeapplicationactual;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Taranveer on 2014-07-22.
*/
public class TheFragmentActivityManager extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
Bundle args = getIntent().getExtras();
if(findViewById(R.id.container) != null){
if(args != null){
if(args.getInt("randomjoke") == 1){
RandomJokeFragment randomJokeFragment = new RandomJokeFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container, randomJokeFragment)
.commit();
}
}
}
if(findViewById(R.id.container) != null){
if(args!=null){
if(args.getInt("listofjoketypes") == 2){
ListOfJokeTypesFragment listOfJokeTypesFragment = new ListOfJokeTypesFragment();
getFragmentManager().beginTransaction()
.replace(R.id.container,listOfJokeTypesFragment)
.commit();
}
}
}
}
}
The relevant XML:
joke_type_fragment.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">
<ListView
android:id="#+id/jokeTypeListView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_margin="5dp"
android:gravity="center_vertical"
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#eeeeee"
android:textStyle="bold"
android:layout_margin="5dp"
android:padding="5dp"
android:background="#2299dd"
android:textSize="20sp"
android:text="Main Activity Items"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rowForMainList"/>
</LinearLayout>
</LinearLayout>
better to put these lines
JokeListData jokeListData = mList.get(position);
holder.mTextView.setText(jokeListData.getListName());
inside if(convertView == null) condition
beforr#Override
public int getCount() {
return super.getCount();
}
remove this line
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
Replace
#Override
public int getCount() {
return super.getCount();
}
With something like
#Override
public int getCount() {
return mySourceArrayList.getCount();
}

Categories

Resources