I'm using slidemenu in my project.
In my fragment i have a listview that reads some data from db.
My fragment:
package ir.monocode.azmooneEstekhdami;
import ir.monocode.azmoonEstekhdami.R;
import java.util.ArrayList;
import android.app.Fragment;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class QuestionsFragment extends Fragment {
public QuestionsFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_questions, container, false);
/******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
// setListData();
// CustomListViewValuesArr.clear();
MySQLiteHelper db = new MySQLiteHelper(getActivity());
ArrayList<CatsModel> CustomListViewValuesArr = db.getAllCelebs();
Resources res = getResources();
// now you must initialize your list view
ListView listview = (ListView) view.findViewById(R.id.listView1);
//listview.setFastScrollEnabled(true);
/**************** Create Custom Adapter *********/
CustomAdapter adapter = new CustomAdapter(getActivity(),CustomListViewValuesArr, res);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// do things with the clicked item
Toast.makeText(getActivity(), ""+ position, Toast.LENGTH_LONG).show();
}
});
return view;
}
}
My fragment layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dedede"
android:orientation="vertical" >
<ImageView
android:id="#+id/cimageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/top"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp" >
</ListView>
</LinearLayout>
But when i want to use onitemclicklistener it doesn`t work. Where is my problem?
As you can see i use customapater and
public void onItemClick(int mPosition) {
// TODO Auto-generated method stub
}
in my main activity.
You need to add these properties for your custom list item row layout widgets which is already inflated in getView() method by you.
android:focusable="false"
android:focusableInTouchMode="false"
Related
So I am trying to set a OnItemClickListener to my ListView. But it doesn't get called at all. I searched for some answers allready but none of them worked for me. (Everything should be not focusable/clickable)
The Listview itself looks like this:
Here is my code:
My ListView in a Fragment:
package com.example.efahrtenbuchapp.ui.table;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import com.example.efahrtenbuchapp.R;
import com.example.efahrtenbuchapp.eFahrtenbuch.Fahrt;
import com.example.efahrtenbuchapp.eFahrtenbuch.FahrtListAdapter;
import com.example.efahrtenbuchapp.eFahrtenbuch.FahrtListenAdapter;
import com.example.efahrtenbuchapp.http.json.JSONConverter;
import com.example.efahrtenbuchapp.http.HttpRequester;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class TableFragment extends Fragment {
private TableViewModel tableViewModel;
private List<FahrtListAdapter> list;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
tableViewModel = ViewModelProviders.of(this).get(TableViewModel.class);
View root = inflater.inflate(R.layout.fragment_table, container, false);
getActivity().setContentView(R.layout.fragment_table);
ListView lv = root.findViewById(R.id.listviewidfrag);
HttpRequester.simpleJsonArrayRequest(getActivity(), "http://10.0.2.2:8080/loadFahrtenListe?kennzeichen=B OB 385", jsonResponse -> {
Log.d("onCreate: ", jsonResponse.toString());
List<FahrtListAdapter> list = JSONConverter.toJSONList(jsonResponse).stream()
.map(json -> (Fahrt) JSONConverter.createFahrtFromJSON(json))
.peek(fahrt -> Log.d("TABLEFRAGMENT", fahrt.toString()))
.map(fahrt -> new FahrtListAdapter(fahrt))
.collect(Collectors.toList());
refreshList(lv, list);
}, null);
FahrtListenAdapter adapter = new FahrtListenAdapter(getActivity(), R.layout.fahrt_list_adapter, new ArrayList());
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "DDD", Toast.LENGTH_LONG);
System.out.println("dddddd");
Log.d("KLICKED ON: ", "Item: " + list.get(position).toString());
}
});
return root;
}
public void message(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
public void refreshList(View root, List<FahrtListAdapter> list){
this.list = list;
ListView lv = getActivity().findViewById(R.id.listviewidfrag); //R.layout.fahrt_list_adapter
ArrayAdapter adapter = new FahrtListenAdapter(getActivity(), R.layout.fahrt_list_adapter, list);
lv.setAdapter(adapter);
}
}
The Adapter:
package com.example.efahrtenbuchapp.eFahrtenbuch;
import android.content.Context;
import android.util.Log;
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 com.example.efahrtenbuchapp.R;
import java.util.List;
public class FahrtListenAdapter extends ArrayAdapter<FahrtListAdapter> {
private final int resource;
private Context context;
public FahrtListenAdapter(#NonNull Context context, int resource, List<FahrtListAdapter>
objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
String km = getItem(position).getKm();
String ziel = getItem(position).getZiel();
String datum = getItem(position).getDatum();
FahrtListAdapter fla = new FahrtListAdapter(datum, ziel, km);
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.fahrt_list_adapter, parent, false);
Log.d("", "getView: focusable = " + convertView.hasFocusable());
Log.d("", "getView: clickable = " + convertView.isClickable());
Log.d("", "getView: clickable = " + convertView.isFocusableInTouchMode());
TextView tv1 = convertView.findViewById(R.id.tv1);
TextView tv2 = convertView.findViewById(R.id.tv2);
TextView tv3 = convertView.findViewById(R.id.tv3);
tv1.setText(ziel);
tv2.setText(datum);
tv3.setText(km);
return convertView;
}
}
The Layout of the Adapter:
<?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:layout_marginTop="2dp"
android:background="#80FFFFFF"
android:orientation="horizontal"
android:weightSum="100"
android:descendantFocusability = "blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false">
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="66.6"
android:gravity="center"
android:text="textview1"
android:textAlignment="center"
android:focusable="false"
android:descendantFocusability = "blocksDescendants"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="33.3"
android:orientation="vertical"
android:focusable="false"
android:descendantFocusability = "blocksDescendants">
<TextView
android:id="#+id/tv2"
android:layout_width="match_parent"
android:layout_height="30dp"
android:gravity="center"
android:text="textview2"
android:focusable="false"
android:descendantFocusability = "blocksDescendants" />
<TextView
android:id="#+id/tv3"
android:layout_width="match_parent"
android:layout_height="30dp"
android:gravity="center"
android:text="textview3"
android:focusable="false"
android:descendantFocusability = "blocksDescendants" />
</LinearLayout>
</LinearLayout>
the layout of the fragment:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:descendantFocusability="blocksDescendants"
android:focusable="false">
<ListView
android:id="#+id/listviewidfrag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability = "blocksDescendants"
android:focusable="false"/>
</androidx.constraintlayout.widget.ConstraintLayout>
As stated by omer.ersoy the onClick-Method worked for me.
So I added to my code in the Adapter:
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("ADAPTER", "onClick: ELEMENT= " + datum);
}
});
This is my code which I used to make my data fetched from my data base in form of a list.But it is refreshing at all time when scroll down after a scrolled up for an instant . I need to make the refresh avail only when it is at top.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
}
my xml file
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</RelativeLayout>
Change your xml layout so SwipeRefreshLayout only wrap a scrollable view (your case the ListView).
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.enhancedListView.EnhancedListView
android:id="#+id/listaNoticias"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="5dp" >
</com.enhancedListView.EnhancedListView>
</android.support.v4.widget.SwipeRefreshLayout>
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.principal, container, false);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark,
android.R.color.holo_red_dark,
android.R.color.holo_blue_dark,
android.R.color.holo_orange_dark); (...)
#Override
public void onRefresh() {
new myTask().execute();
}
I found my own solution for the question above. We can solve the issue by change the above code like below.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment implements AbsListView.OnScrollListener {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
private int preLast;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
listView.setOnScrollListener(this);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (view.getId() == R.id.post) {
if (firstVisibleItem == 0) {
swipe.setEnabled(true);
int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (preLast != lastItem) {
preLast = lastItem;
//Toast.makeText(getActivity(), "In Last", Toast.LENGTH_SHORT).show();
}
}else{
}
} else {
swipe.setEnabled(false);
}
}
}
}
This is a bit old, but in 2019 this is the correct answer: you have to include RecyclerView inside of NestedScrollView in order for SwipeRefreshLayout to behave properly, like this:
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
add this lines of code
note : LinearLayoutManager should be define separately
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mSwipeRefreshLayout.setEnabled
(mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
}
});
findFirstCompletelyVisibleItemPosition() == 0 means at the top of recyclerview
I am new to android programming and I seem to have come at a stand still for several days now. I am having trouble finding a solution to my problem and tried many different solutions without success. As the title suggests, my code runs successfully but the ListView does not show up on the selected Tabs. Any suggestions of tips would be helpful.
ItemGuide.Java ------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ItemGuide extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), LeatherTab.class, null);
mTabsAdapter.addTab(bar.newTab().setIcon(R.drawable.leathertab_image), SilverTab.class, null);
}
}
LeatherTab.java --------------------------------------------------------------
package com.example.alzuni_project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class LeatherTab extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leather_fragment, container, false); //Fragment Layout inflated
TextView text = (TextView) view.findViewById(R.id.boxtest);//TextView for layout testing
text.setText("Hello");
ListView leather_listview = (ListView) view.findViewById(R.id.leather_list); // List is initialized
leather_listview.setAdapter(new LeatherAdapter(getActivity())); //Custom list adapter passes Context
return view;
}
}
LeatherAdapter.java ------------------------------------------------------
package com.example.alzuni_project;
import java.util.ArrayList;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
class LeatherAdapter extends BaseAdapter {
ArrayList<SingleRow> list;
Context context;
public LeatherAdapter(Context c) {
context = c;
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.leather_list_titles);
String[] descriptions = res.getStringArray(R.array.leather_list_description);
int[] images = {R.drawable.belt, R.drawable.wallet, R.drawable.coincase};
for (int i=0;i<images.length;i++) //Was originally 3
{
new SingleRow(titles[i], descriptions[i], images[i]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.leather_title);
TextView description = (TextView) row.findViewById(R.id.leather_description);
ImageView image = (ImageView) row.findViewById(R.id.leather_icon);
SingleRow temp = list.get(position);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;//returns the rootView of single_row.xml
}
}
leatherfragment.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="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/boxtest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#CCDDFF" />
<ListView
android:id="#+id/leather_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/boxtest" />
</RelativeLayout>
SingleRow.java -----------------------------------------------------
package com.example.alzuni_project;
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title=title;
this.description=description;
this.image=image;
}
}
single_row.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="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/leather_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="48dp"
android:contentDescription="#string/todo" />
<TextView
android:id="#+id/leather_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#CCCCCC" />
<TextView
android:id="#+id/leather_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/leather_icon"
android:layout_alignLeft="#+id/leather_icon"
android:layout_alignParentRight="true"
android:layout_below="#+id/leather_title"
android:background="#CCDDFF" />
Your list seems empty , try this in your LeatherAdapter:
list.add(new SingleRow(titles[i],descriptions[i], images[i]));
Inside the for loop .
Here is my code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</android.support.v4.view.ViewPager>
</RelativeLayout>
fragment_view1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/viewOneText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="92dp"
android:layout_marginTop="182dp"
android:text="First View"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/viewOneBtn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/viewOneText"
android:layout_below="#+id/viewOneText"
android:layout_marginTop="17dp"
android:text="Click Here" />
<include layout = "#layout/drop_down"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
custom_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="174dp"
android:text="Custom Fragment"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
MainActivity.java
package com.example.fragmenttest;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private ViewPager viewPager;
private MyAdapter pageAdapter;
private static final int ITEMS = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
pageAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return ITEMS;
}
#Override
public Fragment getItem(int position) {
if(position==0)
{
return new FirstView();
}
else
{
return new SecondView();
}
}
}
public void setCurrentItem (int item, boolean smoothScroll) {
viewPager.setCurrentItem(item, smoothScroll);
}
public void onMenuItemClicked(View view) {
Toast.makeText(this, "LOL", Toast.LENGTH_LONG).show();
}
}
FirstView.java
package com.example.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstView extends DropDownMenu
{
private TextView firstText;
private Button btn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_view1,container,false);
firstText = (TextView)view.findViewById(R.id.viewOneText);
btn = (Button)view.findViewById(R.id.viewOneBtn);
btn.setOnClickListener(new ButtonEvent());
return view;
}
private class ButtonEvent implements OnClickListener
{
}
}
CustomView.java
package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class CustomView extends Fragment
{
private TextView secondText;
private Button secondViewBtn;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.custom_view,container,false);
return view;
}
}
When I click the button in fragment_view1.xml, I need to go to custom_view.xml screen. It is a totally different fragment. How can I do this?
Add this to your OnClickListener:
CustomView cv = new CustomView();
FragmentManager fm= getFragmentManager();
FragmentTransaction ft= fm.beginTransaction();
ft.replace(R.id.custom_view, cv);
ft.commit();
You need to add this to the RelativeLayout in your
custom_view.xml
android:id="#+id/custom_view"
Try this...place inside listener
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
//Create one FrameLayout and give the id as fragment_view in your fragment_view1.xml
and do like below
add this line in your layout fragment_view1.xml
<FrameLayout
android:id="#+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
private class ButtonEvent implements OnClickListener
{
CustomView custFra = new CustomView();
fragmentTransaction.replace(R.id.fragment_view, custFra).commit();
}
[EDIT]: Thank you for all the meaningful answers, the problem is now solved, thank to your help. Similar issue: Android: I am unable to have ViewPager WRAP_CONTENT
I'm trying to implement the UI of my app : I want a ListView with a ViewPager in each row.
Here are my files :
MainActivity.java
package com.condi;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new CardListAdapter(this, getFragmentManager()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
CardListAdapter.java
package com.condi;
import java.util.List;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class CardListAdapter extends BaseAdapter {
private Context context;
private FragmentManager fragmentManager;
private List<Profile> profiles;
CardListAdapter(Context context, FragmentManager fragmentManager) {
this.context = context;
this.fragmentManager = fragmentManager;
this.profiles = new DatabaseHelper(context).getProfiles();
}
#Override
public int getCount() {
return profiles.size();
}
#Override
public Profile getItem(int position) {
return profiles.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = View.inflate(context, R.layout.profile_card, null);
CardPagerAdapter mCardPagerAdapter = new CardPagerAdapter(
fragmentManager);
ViewPager viewPager = (ViewPager) convertView.findViewById(R.id.pager);
viewPager.setAdapter(mCardPagerAdapter);
viewPager.setId(R.id.pager);
return convertView;
}
}
profile_card.xml (issue came from wrap_content).
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</FrameLayout>
CardPagerAdapter.java
package com.condi;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
public class CardPagerAdapter extends FragmentPagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
Fragment1.java
package com.condi;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.preference_category, container, false);
}
}
Fragment2.java
package com.condi;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
public Fragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.preference_category, container, false);
}
}
The database that furnishes the profiles is working well.
The problem is that I am getting an empty list with the correct number of item, but no ViewPager displayed at all. screenshot of my app
What am I doing wrong ?
Try to change your ViewPager's height in xml. wrap_content does not work.
To make is clear, its a bad practice to use viewpagers inside a list view as this design hits the ui performance. The best way to handle this problem is:
To do manual inflation of viewpagers and add to a layout.
Add a unique id to each viewpager so that it is identified uniquely by the system.
Extend a custom viewpager and onmeasure() measure the child layout inflated at the page selected. You can do this by setting a callback in your custom viewpager and trigger the callback from viewpagers onPageScrolled listener, passing the position to identify the child layout.
In your onMeaure() method measure the child layout height and set it as the viewpagers height using super.onMeasure() passing the newly measured specs.
Key points to make a note of :
N.B. Set a unique id to the viewpager inflated by you.
try this problem in layout height
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
It's a bad practice to use wrap_content for your viewpager's height. You can use match_parent or a static dp for your viewpager's height.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:background="#drawable/card_background"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
If it's a must to use wrap_content for your viewpager's height you can override your viewpager's onMeasure() and calculate height. Here's an example below about it.
Android: I am unable to have ViewPager WRAP_CONTENT
I hope this'll help you.
ViewPager doesn’t support wrap_content as it stands now because it doesn’t load all of its children at the same time, meaning it can’t get an appropriate measurement. You must fix View's height in your xml or create a custom ViewPager (read more at here) and use it in your xml
Try using a fixed height ViewPager inside the ListView.ViewPager does not support wrap_content