Android ViewPager doesn't show Fragment - java

I'm trying to let my ViewPager to show my Fragments, however, it doesn't seem to do the work. All it does is just not showing anything, not even a height. Can someone tell me what step am I missing? thanks
main_activity.xml:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackground">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottomNavigation" />
<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
android:id="#+id/bottomNavigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
AHBottomNavigation bottomNavigation;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottomNavigation);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
// Buttom Navigation
// Add items
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Rooms", R.drawable.ic_chatboxes);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("User", R.drawable.ic_contact_outline);
bottomNavigation.addItem(item1);
bottomNavigation.addItem(item2);
// Customize Buttom Navigation
bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
// Set colors
bottomNavigation.setAccentColor(ContextCompat.getColor(this, R.color.colorAccent));
bottomNavigation.setInactiveColor(ContextCompat.getColor(this, R.color.colorTabDefault));
// Set background color
bottomNavigation.setDefaultBackgroundColor(ContextCompat.getColor(this, R.color.colorBackground));
bottomNavigation.setTranslucentNavigationEnabled(true);
// Viewpager setup
pagerAdapter.addFragment(new Rooms(), "Rooms");
pagerAdapter.addFragment(new User(), "User");
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(bottomNavigation.getCurrentItem());
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
bottomNavigation.setCurrentItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
viewPager.setCurrentItem(position, true);
return true;
}
});
}
ViewPagerAdapter.java:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private Fragment currentItem;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (getCurrentItem() != object) {
currentItem = ((Fragment) object);
}
super.setPrimaryItem(container, position, object);
}
public Fragment getCurrentItem() {
return currentItem;
}
}

Related

Title gets cut when using TabPageIndicator

I am using TabPageIndicator in a fragment and sometimes the text gets cut off. Is this possible to adjust somehow? In the example below the complete title is "역사/문화/종교" but it just displays "역사/문화/". When localizing the app then this occurs at various tabs throughout the application.
XML
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/roundcorner"/>
JAVA
public class SearchResultActivity extends FragmentActivity {
private TabPageIndicator indicator;
private ViewPager pager;
String mCity;
private static final String[] tabTitle = new String[] {"쇼핑", "역사/문화/종교", "자연/휴양", "전망", "오락시설"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
mCity = intent.getExtras().getString("mCity");
setContentView(R.layout.activity_search_result);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
indicator = (TabPageIndicator)findViewById(R.id.indicator);
pager = (ViewPager)findViewById(R.id.pager);
pager.setBackgroundResource(R.drawable.img_bg_background);
pager.setAdapter(adapter);
indicator.setViewPager(pager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return SearchResultFragment.newInstance(tabTitle[position % tabTitle.length], mCity);
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitle[position % tabTitle.length].toUpperCase();
}
#Override
public int getCount() {
return tabTitle.length;
}
}}

fragment disappears

I have a fragment alertsfragment.java , which has a grid view layout, when I open that , it works normally , but as soon I swipe between other tabs ,it vanishes away .
to explain more , I have an activity tab layout which has a tab on the bottom , and its first tab opens two fragments alertsfragment and friendsfragment,
I am including the code and the screenshot for simplification.
staring with mapfragment which contains two fragment alert frag and friends frag
mapfragment.java
public class MapFragment extends Fragment{
TabLayout tabLayout;
ViewPager viewPager;
public MapFragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View ROOTView =inflater.inflate(R.layout.mapfragment,container,false);
viewPager = (ViewPager)ROOTView.findViewById(R.id.viewpager2);
setupViewPager(viewPager);
tabLayout = (TabLayout)ROOTView.findViewById(R.id.tabs);
//viewPager.setOffscreenPageLimit(2);
tabLayout.setupWithViewPager(viewPager);
return ROOTView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
adapter.addFragment(new FriendsFragment(), "FRIENDS");
adapter.addFragment(new AlertsFragment(), "Alerts");
setRetainInstance(true);
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
alertsfragment.java
public class AlertsFragment extends Fragment{
GridView grid;
final String[] name = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final String[] status = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final String[] place = {
"Google",
"Github",
"Instagram",
"Facebook",
} ;
final int[] imageId = {
R.drawable.logo,
R.drawable.logo,
R.drawable.logo,
R.drawable.logo,
};
public AlertsFragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View alertsfrag =inflater.inflate(R.layout.alertsfragments,container,false);
grid=(GridView) alertsfrag.findViewById(R.id.grid);
CustomGrid adapter = new CustomGrid(getActivity(), name,status,place,imageId);
grid=(GridView)alertsfrag.findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "You Clicked at " +name[+ position], Toast.LENGTH_SHORT).show();
}
});
return alertsfrag;
}
}
its customadapter
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] name;
private final String[] status;
private final String[] place;
private final int[] Imageid;
public CustomGrid(Context c,String[] name,String[] status,String[] place,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.name = name;
this.status = status;
this.place = place;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.length;
// return status.length;
// return place.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
TextView textView1 = (TextView) grid.findViewById(R.id.grid_text1);
TextView textView2 = (TextView) grid.findViewById(R.id.grid_text2);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(name[position]);
textView1.setText(status[position]);
textView2.setText(place[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
its XML
alertsfrag.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlertsFragment" >
<GridView
android:layout_marginTop="60dp"
android:numColumns="2"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/grid"
/>
</LinearLayout>
mainTabLayout
TabLayout.java
public class Bottom_Tabs_Activity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_friends,
R.drawable.ic_map,
R.drawable.ic_status,
R.drawable.ic_chat,
R.drawable.ic_profile
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
setupViewPager(viewPager);
else {
Log.e("test", "i am null");
}
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new MapFragment(),"MAPS");
adapter.addFrag(new PeopleFragment(),"PEOPLE");
adapter.addFrag(new HomeFragment(),"HOME");
adapter.addFrag(new ChatFragment(),"CHAT");
adapter.addFrag(new ProfileFragment(),"PROFILE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
}
}
TabLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".9"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
app:tabMode="fixed"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#000000"
app:tabIndicatorColor="#ff1232"
app:tabGravity="fill"
/>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_gravity="bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
</android.support.design.widget.AppBarLayout>
</LinearLayout>
</LinearLayout>
Screenshots
Before and after
any kind of help would be appreciated:)
needed to use getChildFragmentManager() instead of getFragmentManager() for placing and managing Fragments inside of a Fragment.
see mapfragment.java , there I used this and the problem got solved
Do not use FragmentPagerAdapter.
you have to use FragmentStatePagerAdapter on ViewPagerAdapter Class.
class ViewPagerAdapter extends FragmentStatePagerAdapter
{
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
}

Sliding Tabs with RecycleView Fragments and Swipe to Refresh

i'm having some issues implementing a Sliding Tabs activity that contains 2 Fragments and a Swipe Down to Refresh layout, namely implementing the Swipe Down to Refresh part (the rest is working just fine).
First here are my XML files.
The Main Activity XML , which contains the ViewPager wrapped in an SwipeRefreshLayout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.popal.soul.MovieListActivityTEST">
<com.example.popal.soul.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/ColorPrimary"/>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipeContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
</android.support.v4.widget.SwipeRefreshLayout>
And the first tab XML , one of the 2 tabs (both are similar, so i`ll only post one)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Now, my main activity, which handles the ViewPager, Adapter an the SlidingTabsLayout.
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
And finally, my fragment for the first Tab
public class Tab1 extends Fragment {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
private SwipeRefreshLayout swipeContainer;
private List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
private ProgressBar progressBar;
private final static String MOVIES_POST_REQUEST ="//Long String, Edited out since it`s not relevant"
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
progressBar.setVisibility(View.VISIBLE);
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
movieListAdaptor.clear();
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
swipeContainer.setRefreshing(false);
}
});
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
The issue is, i'm getting a NULL Pointer Exception at swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {...} method, which i guess is because the Swipe-to-Refresh layout is in the main activity XML, and not the tabs fragment. So what is the proper way to implement this ? I also tried implementing a Swipe to refresh layout in one of the Tabs XML instead of wrapping the ViewPager in it, like above, but it would crash when swiping from tab to another.
Here`s the code from the entire fragment in Tab1, for tobs answer below
public class MoviesTabFragment extends Fragment implements Refreshable {
public MovieListAdapter movieListAdaptor;
public RecyclerView recycleList;
//private SwipeRefreshLayout swipeContainer;
public List<MovieListAdapter.MovieDetails> movieList = new ArrayList<MovieListAdapter.MovieDetails>();
public ProgressBar progressBar;
public final static String MOVIES_POST_REQUEST ="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1, container, false);
recycleList = (RecyclerView) v.findViewById(R.id.cardList);
progressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycleList.setLayoutManager(llm);
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
return v;
}
#Override
public void refresh() {
new Send_data_to_server().execute(MOVIES_POST_REQUEST);
}
public class Send_data_to_server extends AsyncTask<String, Void, String> {
private String data_poster;
private String data_fanart;
// protected void onPreExecute() {
// progressBar.setVisibility(View.VISIBLE);
// }
protected String doInBackground(String... params)
{
String jason_data = params[0];
HttpClient http_con = new HttpClient();
String output_from_server = http_con.establish_con(jason_data);
Log.i("DataFromServer", output_from_server);
JSONObject json_Obj = null;
JSONObject child_obj = null; //creating the "result" object in the main JSON Object
try {
json_Obj = new JSONObject(output_from_server);
child_obj = create_subObject("result", json_Obj);
JSONArray jsonArray = child_obj.optJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title_data = jsonObject.optString("label").toString();
String plot_data = jsonObject.optString("plot").toString();
String year_data = jsonObject.optString("year").toString();
String movie_id_data = jsonObject.optString("movieid").toString();
String imdb_score = jsonObject.optString("rating").toString();
String imdb_score_short = imdb_score.substring(0, 3);
JSONObject child_obj2 = create_subObject("art", jsonObject);
data_poster = child_obj2.optString("poster").toString();
data_fanart = child_obj2.optString("fanart").toString();
JSONEncodePosterFanart encodePosterFanart = new JSONEncodePosterFanart();
String jason_dataPoster = encodePosterFanart.GetPosterFanartEncodedURL(data_poster);
String jason_dataFanart = encodePosterFanart.GetPosterFanartEncodedURL(data_fanart);
HttpClient http = new HttpClient();
String output_from_serverPoster = http.establish_con(jason_dataPoster);
HttpClient http2 = new HttpClient();
String output_from_serverFanart = http2.establish_con(jason_dataFanart);
JSONPosterFanart poster_fanart = new JSONPosterFanart();
String post_dl = poster_fanart.GetPosterFanart(output_from_serverPoster);
JSONPosterFanart poster_fanart2 = new JSONPosterFanart();
String fanart_dl = poster_fanart2.GetPosterFanart(output_from_serverFanart);
if (null == movieList) {
movieList = new ArrayList<MovieListAdapter.MovieDetails>();
}
MovieListAdapter.MovieDetails item = new MovieListAdapter.MovieDetails(title_data+" ("+year_data+")", post_dl, fanart_dl,plot_data,movie_id_data,imdb_score_short);
movieList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return output_from_server;
}
protected void onPostExecute(String output_from_server) {
super.onPostExecute(output_from_server);
//progressBar.setVisibility(View.INVISIBLE);
movieListAdaptor = new MovieListAdapter(getActivity(), movieList);
recycleList.setAdapter(movieListAdaptor);
}
private JSONObject create_subObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName); //getJSONObject returns the value from tagName (in our case jason_Obj that is being passed ar a param)
return subObj;
}
}
}
And the RecycleView adapter:
public class MovieListAdapter extends RecyclerView.Adapter<MovieListAdapter.MovieViewHolder> {
public List<MovieDetails> movieList;
private Context mContext;
public MovieListAdapter(Context mContext, List<MovieDetails> movieList) {
this.mContext = mContext;
this.movieList = movieList;
}
#Override
public int getItemCount() {
return movieList.size();
}
public void clear() {
movieList.clear();
notifyDataSetChanged();
}
#Override
public MovieViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout_movies_list, viewGroup, false);
return new MovieViewHolder(itemView);
}
#Override
public void onBindViewHolder(MovieViewHolder movieViewHolder, int i) {
MovieDetails mdet = movieList.get(i);
String fanart = "http://192.168.1.128/"+mdet.getImageViewFanart();
String poster = "http://192.168.1.128/"+mdet.getImageViewPoster();
Log.i("fanart", fanart);
Log.i("poster", poster);
movieViewHolder.vTitle.setText(mdet.Title);
Picasso.with(mContext).load(poster)
.resize(500, 746)
.error(R.drawable.poster_placeholder)
.placeholder(R.drawable.poster_placeholder)
.into(movieViewHolder.vPoster);
Picasso.with(mContext).load(fanart)
.resize(960, 540)
.error(R.drawable.fanart_placeholder)
.placeholder(R.drawable.fanart_placeholder)
.into(movieViewHolder.vFanart);
movieViewHolder.vplot = mdet.getPlot();
movieViewHolder.vmovie_id = mdet.getMovie_id();
}
public class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView vTitle;
protected ImageView vPoster;
protected ImageView vFanart;
protected String vplot;
protected String vmovie_id;
protected String vimdb_score;
public MovieViewHolder(View v)
{
super(v);
vplot = new String();
vmovie_id = new String();
vimdb_score = new String();
vTitle = (TextView) v.findViewById(R.id.title);
vPoster = (ImageView) v.findViewById(R.id.imageViewPoster);
vFanart = (ImageView) v.findViewById(R.id.imageViewFanart);
v.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getLayoutPosition();
MovieDetails mov = movieList.get(position);
Intent intent = new Intent(mContext, MovieDetailsPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("movieid", mov.getMovie_id());
bundle.putString("plot", vplot);
bundle.putString("fanart_path", mov.getImageViewFanart());
bundle.putString("imdb_score", mov.getImdb_score());
intent.putExtras(bundle);
mContext.startActivity(intent);
}
}
public static class MovieDetails {
protected String Title;
protected String imageViewPoster;
protected String imageViewFanart;
protected String plot;
protected String movie_id;
protected String imdb_score;
public MovieDetails(String Title, String imageViewPoster,String imageViewFanart, String plot, String movie_id ,String imdb_score)
{
this.Title = Title;
this.imageViewPoster = imageViewPoster;
this.imageViewFanart = imageViewFanart;
this.plot = plot;
this.movie_id = movie_id;
this.imdb_score = imdb_score;
}
public String getTitle() {return Title;}
public String getImageViewPoster() {
return imageViewPoster;
}
public String getImageViewFanart() {
return imageViewFanart;
}
public String getPlot() {return plot;}
public String getMovie_id() {return movie_id;}
public String getImdb_score() {return imdb_score;}
}
}
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[];
int NumbOfTabs;
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0)
{
MoviesTabFragment moviesTabFragment = new MoviesTabFragment();
return moviesTabFragment;
}
else
{
TVShowsTabFragment TVShowsTabFragment = new TVShowsTabFragment();
return TVShowsTabFragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}
You're getting the NullPointerException because you inflate your fragment layout from R.layout.tab_1 which does not contain a SwipeRefreshLayout.
If you want the layout to be the parent of your ViewPager, I would recommend you to move your code which manages the RefreshLayout to the MainActivity:
public class MovieListActivityTEST extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SwipeRefreshLayout refreshLayout;
SlidingTabLayout tabs;
CharSequence Titles[]={"Home","Events"};
int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list_activity_test);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
// Assign your refresh layout
refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Refreshable r = (Refreshable) adapter.getItemAt(pager.getCurrentItem());
r.refresh();
}
});
}
where each of your tab fragments implements a Refreshable interface:
public interface Refreshable {
void refresh();
}
and your adapter keeps track on all fragments:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
// list that keeps references to all attached Fragments
private SparseArray<Fragment> pages = new SparseArray<>();
...
public Fragment getItem(int position) {
Fragment f;
if(position == 0) {
...
} else { ... }
// add fragment to the list
pages.put(position, f);
}
public void destroyItem(ViewGroup container, int position, Object object) {
// remove fragment from list if it existed
if(pages.indexOfKey(position) >= 0) {
pages.remove(position);
}
super.destroyItem(container, position, object);
}
// return the attached Fragment that is associated with the given position
public Fragment getItemAt(int position) {
return pages.get(position);
}
}

Correctly implementing PagerAdapter in Android

I have problems with implementation of my custom PagerAdapter and using it with a ViewPager.
This sample PagerAdapter has 10 items, every item is a button with it's index as text.
When I run my program, I see a button with text '1' insted of '0'. And when I swipe to other items I get only blank views. When I swipe backwards sometimes I see a button with some number, but it disappears (maybe it is destroying and I remove it from the container), and sometimes I see a button with a number, but the number changes after the swipe (I think I create a new Button and I add it to the container, and for some reasons the viewpager shows this new button).
How can I fix this implementation? I haven't seen difference in examples.
My PagerAdapter implementation:
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o.getClass()==view.getClass();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ActionBar.LayoutParams(-1,-1);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
container.addView(button);
return button;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((Button)object);
}
}
And my Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter());
}
}
Here is complete code:
xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.androidviewpagerapp.MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MyPagerAdapter class:
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o==view;
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
final int page = position;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(container.getContext(), "You clicked: " + page + ". page.", Toast.LENGTH_SHORT).show();
}
});
container.addView(button);
return button;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((Button)object);
}
}
MainActivity:
import android.support.v4.view.ViewPager;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
ViewPager viewPager;
MyPagerAdapter myPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
myPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(myPagerAdapter);
}
}
You will see that Buttons are full screen. To avoid that you need to create some layout (like LinearLayout) and add button to that layout.
Example:
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o==view;
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
LinearLayout layout = new LinearLayout(container.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//add buton to layout
layout.addView(button);
final int page = position;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(container.getContext(), "You clicked: " + page + ". page.", Toast.LENGTH_SHORT).show();
}
});
//to container add layout instead of button
container.addView(layout);
//return layout instead of button
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//cast to LinearLayout
container.removeView((LinearLayout)object);
}
}
if you want to inflate views in pager you must have to implement two methods.
instantiateItem and destroyItem
public class DialogPagerAdapter extends PagerAdapter {
private Context mContext;
//view inflating..
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.account_dialog_signin_viewpagers,
collection, false);
TextView tvLabel = (TextView) layout.findViewById(R.id.textView);
switch (position) {
case 0:
tvLabel.setText("Log In");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
break;
case 1:
tvLabel.setText("Sign Up");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
break;
case 2:
tvLabel.setText("Send Reset Link");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//onOptionClickForgot.OnOptionClick();
}
});
break;
}
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Simply call it like
viewPager.setAdapter(new DialogPagerAdapter);
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/dialog_button_height"
android:paddingLeft="#dimen/dimen_2"
android:paddingRight="#dimen/dimen_2"
android:minHeight="#dimen/dialog_button_height">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_medium" />
</RelativeLayout>
Here i post ViewPagerAdapter that attached between TabLayout to ViewPager
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<String> titleList = new ArrayList<>();
List<Fragment> fragment = new ArrayList<>();
public void addFragment(String title, Fragment fragment) {
this.titleList.add(title);
this.fragment.add(fragment);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragment.get(position);
}
#Override
public int getCount() {
return titleList.size();
}
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
How to use ViewPagerAdapter.
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment("TAB 1", new YOUR_FRAGMENT1());
adapter.addFragment("TAB 2", new YOUR_FRAGMENT2());
// Keep adding fragments.
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);

Cannot Reach Breakpoint / Intent Will Not Launch

I'm attempting to launch an intent in my Home.java:
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
It should be initiated by:
package com.idg.omv.ui;
import com.idg.omv.domain.Video;
public interface VideoClickListener {
public void onVideoClicked(Video video);
}
which is initiated by listView.setOnVideoClickListener(this); in my Home.java
However I cannot seem to reach onVideoClicked when setting a breakpoint in Home.java and I'm unsure why.
FULL SOURCE:
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "AIzaSyC0Te2pyooXzuyLaE6_SsFlITKCwjj55fI";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "idconex";
Activity activity;
int imageArray[];
String[] stringArray;
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
//mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
// Here we are adding this activity as a listener for when any row in
// the List is 'clicked'
// The activity will be sent back the video that has been pressed to do
// whatever it wants with
// in this case we will retrieve the URL of the video and fire off an
// intent to view it
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
// This is the interface method that is called when a video in the listview
// is clicked!
// The interface is a contract between this activity and the listview
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
// setOnPageChangeListener(mPageChangeListener);
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP‎", "TimMcGrawVEVO‎", "TiestoVEVO‎",
"EminemVEVO‎" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
// Calc if swipe was left to right, or right to left
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
VideoListView.java
public class VideosListView extends ListView implements android.widget.AdapterView.OnItemClickListener {
private List<Video> videos;
private VideoClickListener videoClickListener;
public VideosListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VideosListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideosListView(Context context) {
super(context);
}
public void setVideos(List<Video> videos){
this.videos = videos;
VideosAdapter adapter = new VideosAdapter(getContext(), videos);
setAdapter(adapter);
// When the videos are set we also set an item click listener to the list
// this will callback to our custom list whenever an item it pressed
// it will tell us what position in the list is pressed
setOnItemClickListener(this);
}
// Calling this method sets a listener to the list
// Whatever class is passed in will be notified when the list is pressed
// (The class that is passed in just has to 'implement VideoClickListener'
// meaning is has the methods available we want to call)
public void setOnVideoClickListener(VideoClickListener l) {
videoClickListener = l;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
// When we receive a notification that a list item was pressed
// we check to see if a video listener has been set
// if it has we can then tell the listener 'hey a video has just been clicked' also passing the video
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
if(videoClickListener != null){
videoClickListener.onVideoClicked(videos.get(position));
}
}
}
My Source:
https://www.dropbox.com/s/irab3x18nhj4twt/idg.zip
Working Example:
http://blog.blundell-apps.com/click-item-in-a-listview-to-show-youtube-video/
If the List has clickable elements like ImageViewand Button, when you click on the list it is consumed by the ImageView and Button and your onitemClickListener is never called.
To make it work add android:clickable="false", android:focusable="false" and
android:focusableInTouchMode="false" to each of those Buttons and ImageViews in custom adapter view.
list_item_user_video.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.idg.omv.ui.widget.UrlImageView
android:id="#+id/userVideoThumbImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/black"
android:contentDescription="YouTube video thumbnail"
android:gravity="center"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
<View android:layout_width="match_parent"
android:layout_height="2dp"
android:visibility="invisible"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/userVideoTitleTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft = "5dip"
android:textSize="16sp"
android:text="Video Title Not Found"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/userVideouploaderTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13sp"
android:paddingLeft = "5dip"
android:layout_below="#id/userVideoTitleTextView"
android:textColor="#android:color/black" />
<Button
android:id="#+id/fav_up_btn1"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_alignParentRight="true"
android:background="#drawable/fav_up_btn1"
android:gravity="right"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="11dp"
android:visibility="invisible"/>
</LinearLayout>
Checkout this article for more info
List view doesn't respond to click

Categories

Resources