Call NavigationDrawer in ALL Activitys - java

I have a NavigationDrawer and I would call it more Activity without having to copy and paste the same code in different classes. Thus, all the code that I would have to paste in the various classes, I put it in a class of its own, called NavDrawer. Here is the code.
NavDrawer
public class NavDrawer extends Activity{
ListView mDrawerList;
DrawerLayout mDrawer;
CustomActionBarDrawerToggle mDrawerToggle;
String[] menuItems;
Intent intent, intent2, intent3, intent4, intent5, intent6;
public void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.item1).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout){
super(
mActivity,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.ns_menu_open,
R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.ns_menu_close));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.ns_menu_open));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the drawer
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
if(position==0) {
//Open an Activity
}
if(position==1) {
//Open an Activity
}
if(position==2) {
//Open an Activity
}
//You should reset item counter
mDrawer.closeDrawer(mDrawerList);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.examplelayout);
getActionBar().setDisplayHomeAsUpEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
_initMenu();
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
}
}
NsMenuAdapter
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public final TextView textCounterHolder;
public ViewHolder(TextView text1, ImageView image1,TextView textcounter1) {
this.textHolder = text1;
this.imageHolder = image1;
this.textCounterHolder=textcounter1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row_counter;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
TextView textcounter1 = (TextView) view.findViewById(R.id.menurow_counter);
view.setTag(new ViewHolder(text1, image1,textcounter1));
}
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.textCounterHolder != null){
if (item.counter > 0){
holder.textCounterHolder.setVisibility(View.VISIBLE);
}else{
holder.textCounterHolder.setVisibility(View.GONE);
}
}
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
NsMenuItemModel
public class NsMenuItemModel {
public int title;
public int iconRes;
public int counter;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header,int counter) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
this.counter=counter;
}
public NsMenuItemModel(int title, int iconRes,boolean header){
this(title,iconRes,header,0);
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
In classes where I want to have the NavigationDrawer I do nothing but extend the class NavigationDrawer, so I have a code like this
public class ExampleClass extends NavDrawer
And when I run the application in the ActionBar visualize the image and NavigationDrawer displayed but is EMPTY. Why?
In addition, in the onCreate of the class NavDrawer I set layout as the layout of an Activity, but if I have to see it in ALL Activity, can not be linked to ONE that A specific layout specific Activity. So I thought I'd create one specifically for the NavigationDrawer, containing one and only its structure. code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
It can work or not?
The layout of the example has a structure similar to this
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#F3F3F4"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" >
</ListView>
</android.support.v4.widget.DrawerLayout>
I hope to have answers to all these and I apologize if my questions may seem trivial but are days that I am looking desperately for a solution, but I just can not. I hope to get answers and help. Thanks in advance.

Related

RecyclerView fragment does not appear

I am trying to create an app to display data in a recyclerview. However, when I run it, the main view is blank (the toolbar and navigation drawer work fine). I have meticulously looked over my code for errors and looked at similar problems, but nothing has worked so far. I have tested the asynctasks, which work, but the info won't display.
Main Activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private static ListView mDrawerList;
private static ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private static String zipCode = "<zipcode>";
private static String street = "<address>";
public static String[] officeList = null;
public static Elements positionLinks = null;
public static int positionSelected;
public CardFragment currentFragment;
public static String[] namesOfCandidates;
public static String[] partiesOfCandidates;
public static String[] occupationsOfCandidates;
public static String[] candidateLinks;
public static boolean gotCandidates = false;
public static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
officeList = getResources().getStringArray(R.array.offices_array);
new AsyncPositions().execute();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, officeList));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_favorite).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}else if(item.getItemId()==R.id.action_settings){
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
// User chose the "Settings" item, show the app settings UI...
return true;
}else if(item.getItemId()==R.id.action_favorite){
Toast.makeText(this, "Favorited", Toast.LENGTH_SHORT).show();
// User chose the "Favorite" action, mark the current item
// as a favorite...
//remember to change this to something else - or maybe just a starred thing for elected officials
return true;
}else {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_bar_buttons, menu);
return super.onCreateOptionsMenu(menu);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
/**
* Swaps fragments in the main content view
*/
private void selectItem(int position) {
positionSelected = position;
//try {
new AsyncCandidates().execute();
/* }
catch(InterruptedException ie){
ie.printStackTrace();
}
catch(ExecutionException ee){
ee.printStackTrace();
}*/
//change the cards to info about candidate
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(officeList[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
}
public String pollingPlaceInfo(){
//document.getElementsByClassName("PollingPlace_polling-place-content_ucq")[0].innerText;
return null;
}
//Gets the information about the specific candidate chosen by the card view
// requests position on drawer and candidate number (index) to pinpoint which candidate
// returns 2d array that contains each issue as well as info about it
public String[][] getIssues(int position, int candidate) {
return null;
}
//asynctask to pull the positions for the nav drawer
private static class AsyncPositions extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
String[] positions;
private String zipCode;
private String street;
private String urlString = "";
private Elements positionLinks;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
zipCode = MainActivity.zipCode;
street = MainActivity.street;
}
#Override
protected Void doInBackground(Void... params) {
Document doc = null;
urlString = "http://votersedge.org/en/ca/search?zip="+zipCode+"&address="+street;
try {
//get initial landing page to find most recent election
doc = Jsoup.connect(urlString)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
//get the link to the most recent election page
String newLink = "";
boolean nullpe = false;
try{
doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
catch(NullPointerException npe) {
newLink = "http://votersedge.org"+doc.body().getElementsByClass("MultipleElections_recent-elections_rsw col-md-12").first().child(1).attr("action");
nullpe = true;
}
if(!nullpe) {
newLink = "http://votersedge.org" + doc.body().getElementsByClass("MultipleElections_upcoming-elections_3C2 col-md-12").first().child(1).attr("action");
}
doc = Jsoup.connect(newLink)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
Elements positionHeaders = doc.getElementsByClass("ContestsList_jurisdiction-group-label_1Kt");
positionLinks = doc.getElementsByClass("ContestsList_contest-link_W44");
//get size of positions list for easy access
int sizeOfList = positionLinks.size()/2;
//create array that will be returned
positions = new String[sizeOfList];
int l = 0;
int k=0;
int j=2;
for(int i=0; i<sizeOfList; i++){
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j);
}
catch(IndexOutOfBoundsException ibe){
k++;
j=2;
l++;
}
try{
doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0);
}
catch(IndexOutOfBoundsException ibe){
j++;
l++;
}
while(!doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).tagName().equals("h4")){
j++;
l++;
}
positions[i] = positionHeaders.eq(l).text() + " " +doc.getElementsByClass("ContestsList_accordion-content_1rY card-content").first().child(k).child(j).child(0).child(0).child(1).text();
j++;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.officeList = positions;
MainActivity.mDrawerList.setAdapter(new ArrayAdapter<>(MainActivity.context,
R.layout.drawer_list_item, MainActivity.officeList));
MainActivity.positionLinks = positionLinks;
pdLoading.dismiss();
}
}
private class AsyncCandidates extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(MainActivity.context);
private Elements positionElements;
private int position;
private String[] namesOfCandidates;
private String[] partiesOfCandidates;
private String[] occupationsOfCandidates;
private String[] candidateLinks;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.setCanceledOnTouchOutside(false);
pdLoading.show();
positionElements = MainActivity.positionLinks;
position = MainActivity.positionSelected;
}
#Override
protected Void doInBackground(Void... params) {
Document doc = null;
String link = "http://votersedge.org"+ positionElements.eq(position).attr("href");
try {
doc = Jsoup.connect(link)
.userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36")
.timeout(12000)
.followRedirects(true)
.get();
}
catch(IOException ioe){
ioe.printStackTrace();
}
//getting links for reference for further information gathering
//need to create initial array to get all links (each has 1 duplicate in the array)
// and then create another array to get rid of duplicates
Elements links = doc.body().getElementsByClass("CandidateCard_candidate-link_2m1");
String[] cLinks = new String[links.size()];
for(int i=0; i<links.size(); i++) {
cLinks[i] = "http://votersedge.org" + links.eq(i).attr("href");
}
candidateLinks = new String[links.size()/2];
for(int i=0; i<links.size(); i+=2){
candidateLinks[i/2] = cLinks[i];
}
//getting names of candidates
Elements names = doc.body().getElementsByClass("CandidateCard_candidate-name_234 col-md-12 col-xs-12 col-sm-12 flush-cols");
namesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
namesOfCandidates[i] = names.eq(i).text();
}
//getting political parties of candidates
Elements attributes = doc.body().getElementsByClass("CandidateCard_candidate-attributes_3qD col-md-12 col-xs-12 col-sm-12 flush-cols");
partiesOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
partiesOfCandidates[i] = attributes.eq(i).first().child(0).text()+" Candidate";
if(partiesOfCandidates[i].equals(" Candidate")) partiesOfCandidates[i] = "Candidate";
}
//getting occupations of candidates
occupationsOfCandidates = new String[names.size()];
for(int i=0; i<names.size(); i++){
occupationsOfCandidates[i] = attributes.eq(i).first().child(1).text();
}
gotCandidates = true;
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.namesOfCandidates = namesOfCandidates;
MainActivity.candidateLinks = candidateLinks;
MainActivity.partiesOfCandidates = partiesOfCandidates;
MainActivity.occupationsOfCandidates = occupationsOfCandidates;
Bundle bundle = new Bundle();
bundle.putStringArray("names", namesOfCandidates);
bundle.putStringArray("parties", partiesOfCandidates);
bundle.putStringArray("links", candidateLinks);
bundle.putStringArray("occupations", occupationsOfCandidates);
FragmentManager fm = getSupportFragmentManager();
MainActivity.this.currentFragment = (CardFragment) fm.findFragmentById(R.id.fragmentContainer);
if (MainActivity.this.currentFragment == null) {
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}else{
MainActivity.this.currentFragment = new CardFragment();
MainActivity.this.currentFragment.setArguments(bundle);
fm.beginTransaction()
.replace(R.id.fragmentContainer, MainActivity.this.currentFragment)
.addToBackStack(null)
.commit();
}
pdLoading.dismiss();
}
}
}
CardFragment.java
public class CardFragment extends Fragment {
RecyclerView MyRecyclerView;
String[] namesOfCandidates;
String[] partiesOfCandidates;
String[] occupationsOfCandidates;
String[] candidateLinks;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("test", "fragment has been created");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.getArguments();
namesOfCandidates = this.getArguments().getStringArray("names");
partiesOfCandidates = this.getArguments().getStringArray("parties");
candidateLinks = this.getArguments().getStringArray("links");
occupationsOfCandidates = this.getArguments().getStringArray("occupations");
View view = inflater.inflate(R.layout.fragment_card, container, false);
MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView);
MyRecyclerView.setHasFixedSize(true);
LinearLayoutManager MyLayoutManager = new LinearLayoutManager(getActivity());
MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
if (namesOfCandidates.length > 0 & MyRecyclerView != null) {
MyRecyclerView.setAdapter(new MyAdapter(namesOfCandidates));
}
MyRecyclerView.setLayoutManager(MyLayoutManager);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private String[] list;
public MyAdapter(String[] Data) {
list = Data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.titleTextView.setText(list[position]);
holder.mainTextView.setText(CardFragment.this.partiesOfCandidates[position]+"Candidate\n"+CardFragment.this.occupationsOfCandidates[position]);
holder.arrowImageView.setTag(R.drawable.ic_arrow_forward_black_24dp);
}
#Override
public int getItemCount() {
return list.length;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView titleTextView;
ImageView arrowImageView;
TextView mainTextView;
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView) v.findViewById(R.id.titleTextView);
mainTextView = (TextView) v.findViewById(R.id.mainTextView);
arrowImageView = (ImageView) v.findViewById(R.id.arrowImageView);
arrowImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = (int)arrowImageView.getTag();
if( id == R.drawable.ic_arrow_forward_black_24dp) {
//MOVE TO NEXT SCREEN
}
}
});
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</FrameLayout>
<!-- Action bar -->
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:theme="#style/ThemeOverlay.AppCompat.Light"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
fragment_card.xml
<?xml version="1.0" encoding="utf-8"?>
<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_left_margin"
android:paddingRight="#dimen/activity_right_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
recycle_items.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
android:weightSum="4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:background="#android:drawable/screen_background_dark_transparent"
android:orientation="vertical">
<TextView
android:id="#+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="#dimen/text_size"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3.2"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:id="#+id/mainTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="#dimen/text_size2"
android:layout_gravity="center"
/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.8"
android:gravity="center|right"
android:orientation="horizontal">
<ImageView
android:id="#+id/arrowImageView"
android:layout_width="#dimen/icon_width"
android:layout_height="#dimen/icon_height"
android:padding="#dimen/icon_padding"
android:src="#drawable/ic_arrow_forward_black_24dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Any help is much appreciated!
Maybe the problem is in your conditional checking, as logical AND should be && not &.
I did some more troubleshooting, and after some tinkering I found that getting rid of the MyToolbar object and the ActionBarDrawerToggle the content showed up. Thank you for your help!

Android ViewPager doesn't show Fragment

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;
}
}

Android : Adding a icon indicating counter in Navigation Drawer layout.

I am working on an Android application in which I would like to add an icon on the navigation drawer. I intend to use it for notification messages when the app is opened. The icon would receive notifications from a service, which would be running in parallel. Right now, I am struggling to put the icon in the Navigation drawer, on top right side.
Here is the screenshot of the drawer.
As you can see the red-dot, I am trying to move the red dot to upper-right hand side, which is part of the drawer and has those 3 dots vertically stacked.
Drawer code :
public class DrawerModel {
private String title;
private int icon;
private String count = "0";
private int id;
// boolean to set visiblity of the counter
private boolean isCounterVisible = false;
}
DrawerLoader :
public class DrawerLoader extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private ArrayList<DrawerModel> navDrawerItems;
private DrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawerlayout);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int sectionId = ((DrawerModel) parent.getItemAtPosition(position)).getId();
displayView(position);
Intent intent = new Intent(getApplicationContext(), GroupSectionActivity.class);
intent.putExtra("groupid", groupAccountId);
intent.putExtra("canvasid", canvasId);
intent.putExtra("sectionid", sectionId);
startActivity(intent);
}
}
#Override
public void onBackPressed() {
mDrawerLayout.closeDrawer(mDrawerList);
}
}
}
DrawerListAdapter :
public class DrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<DrawerModel> drawerModelArrayList;
public DrawerListAdapter(Context context, ArrayList<DrawerModel> drawerModelArrayList){
this.context = context;
this.drawerModelArrayList = drawerModelArrayList;
}
#Override
public int getCount() {
return drawerModelArrayList.size();
}
#Override
public Object getItem(int position) {
return drawerModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawout_list_item, null);
}
ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
icon.setImageResource(drawerModelArrayList.get(position).getIcon());
txtTitle.setText(drawerModelArrayList.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(drawerModelArrayList.get(position).isCounterVisible()){
txtCount.setText(drawerModelArrayList.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
drawerlayout.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
I have tried to put it directly in the XML file, but it does not work. Any help would be nice.. Thank you.. :-)

ListView with custom ArrayAdapter setOnItemClickListener doesn't fire

I can't figure out why setOnItemClickListener doesn't work. I have ListView with custom ListItem layout,- and i'd like to start other activity when user click on row.
I saw lots of topic with this problem, but nothing helped.
Screen:
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/notes_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/addNote">
</ListView>
<TextView
android:id="#+id/empty_list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/empty_notes"
android:visibility="gone"
android:gravity="center"
android:layout_above="#+id/addNote"
/>
<Button
android:id="#+id/addNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/add_note"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
list_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="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Note text-->
<TextView
android:id="#+id/noteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold" />
<!-- Note createdAt -->
<TextView
android:id="#+id/noteCreatedAt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/noteText"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip" />
<!-- Note complete -->
<Button
android:id="#+id/btnCompleteNote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Complete" />
</RelativeLayout>
RNoteAdapter.java:
public class RNoteAdapter extends ArrayAdapter<RNote> {
private Context context;
private int resource;
RNote[] data;
private RNoteRepository noteRepository;
public RNoteAdapter(Context context, int resource, RNote[] data) {
super(context, resource, data);
this.context = context;
this.resource = resource;
this.data = data;
this.noteRepository = new RNoteRepository(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RNoteHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(resource, parent, false);
holder = new RNoteHolder();
holder.noteText = (TextView)row.findViewById(R.id.noteText);
holder.noteCreatedAt = (TextView)row.findViewById(R.id.noteCreatedAt);
holder.btnCompleteNote = (Button)row.findViewById(R.id.btnCompleteNote);
row.setTag(holder);
} else {
holder = (RNoteHolder)row.getTag();
}
final RNote note = data[position];
if(note.IsCompleted) {
holder.noteText.setPaintFlags(holder.noteText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.noteText.setText(note.Text);
DateFormat df = new SimpleDateFormat("dd.MM.yyyy в HH:mm");
holder.noteCreatedAt.setText(df.format(note.CreatedAtUtc));
holder.btnCompleteNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
note.IsCompleted = true;
noteRepository.save(note);
RNoteAdapter.this.notifyDataSetChanged();
}
});
return row;
}
static class RNoteHolder {
TextView noteText;
TextView noteCreatedAt;
Button btnCompleteNote;
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
private RNoteRepository _noteRepository = new RNoteRepository(this);
private Button addButton;
private ListView notesList;
RNoteAdapter adapter;
private void init() {
notesList = (ListView)findViewById(R.id.notes_list);
addButton = (Button)findViewById(R.id.addNote);
notesList.setEmptyView(findViewById(R.id.empty_list_item));
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditNoteActivity(0);
}
});
notesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showEditNoteActivity(id);
}
});
}
private void updateData() {
List<RNote> list = _noteRepository.getAll();
RNote[] array = list.toArray(new RNote[list.size()]);
adapter = new RNoteAdapter(this, R.layout.list_row, array);
notesList.setAdapter(adapter);
}
private void showEditNoteActivity(long noteId) {
Intent intent = new Intent(getApplicationContext(), EditNoteActivity.class);
intent.putExtra("noteId", noteId);
startActivityForResult(intent, 1);
}
private void showDialog(String text) {
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
String msg = data.getStringExtra("response");
showDialog(msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
#Override
protected void onResume() {
super.onResume();
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
add
android:descendantFocusability="blocksDescendants"
to your ListView's row root.
The implementation of getItemId of ArrayAdapter returns position and not the id of your RNote, so you probably want to override it to make it return the correct information
set android:focusable="false"
android:focusableInTouchMode="false" to all the clickable views (like button or editText) in your listView item

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