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
Related
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;
}
}
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.. :-)
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.
This is my first experience with android. I'm trying to add items to my ListView.
I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.
I searched around, and I've always found
adapter.notifyDataSetChanged();
but doesn't work for me.
I have created the project with, as I said, Fixed Tabs + Swipe.
I simply want to have listviews which rows have an EditText, a Spinner and a Button.
On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.
my custom Adapter:
package com.andreapivetta.uconverter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;
public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
super(context, resource, bah);
this.context = context;
this.resourceID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resourceID, parent, false);
return rowView;
}
}
fragment_main_dummy.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<ListView
android:id="#+id/unitListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageButton
android:id="#+id/moreImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_input_add" />
</RelativeLayout>
Row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<EditText
android:id="#+id/unitEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/unitSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/unitEditText" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/unitEditText"
android:layout_alignParentRight="true"
android:onClick="removeItem"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_menu_delete" />
</RelativeLayout>
MainActivity...
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
ArrayList<String> myStringArray1 = new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
String[] myStringArray3 = new String[]{"ddd","eeee"};
String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
public static ArrayAdapter<String> adapter;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
//dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
// ListView
ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
myStringArray1.add("mmm");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
unitListView.setAdapter(adapter);
break;
case 2:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
unitListView.setAdapter(adapter);
break;
case 3:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
unitListView.setAdapter(adapter);
break;
case 4:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
unitListView.setAdapter(adapter);
break;
}
unitListView.setOnItemClickListener(listViewOnClickListener);
// ImageButton
ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
moreImageButton.setOnClickListener(moreListener);
return rootView;
}
public OnClickListener moreListener = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myStringArray1.add("Andrea");
adapter.clear();
adapter.addAll(myStringArray1);
adapter.notifyDataSetChanged();
}
};
public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
};
}
}
Note that I'm working only with the first tab right now...
What am I doing wrong? :)
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
I am having makor issues with what seemed a simple GridView issue in that I cannot get my custom ClickListener registering.
I can get a standard click event working but not through my AlbumClickListener so am unable to retrieve my object details as per position clicked.
Tearing my hair out on this as I am normally strictly iOS. PLEASE HELP!!
Album Java Object
package com.pixelperfect.mayday;
public class AlbumGridView extends GridView implements
android.widget.AdapterView.OnItemClickListener {
private List<Album> albums;
private AlbumClickListener albumClickListener;
public AlbumGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public AlbumGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AlbumGridView(Context context) {
super(context);
}
public void setAlbums(List<Album> albums){
this.albums = albums;
MusicGridAdapter adapter = new MusicGridAdapter(getContext(), albums);
setAdapter(adapter);
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 setOnAlbumClickListener(AlbumClickListener l) {
albumClickListener = 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) {
// this is crashing
if(albumClickListener != null){
albumClickListener.onAlbumClicked(albums.get(position));
}
}
}
Album Click Listener
package com.pixelperfect.mayday;
import com.pixelperfect.mayday.Album;
public interface AlbumClickListener {
public void onAlbumClicked(Album album);
}
Music Grid Adapter
package com.pixelperfect.mayday;
public class MusicGridAdapter extends BaseAdapter
{
List<Album> albums;
private LayoutInflater mInflater;
public MusicGridAdapter(Context context, List<Album> albums) {
this.albums = albums;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return albums.size();
}
#Override
public Object getItem(int position) {
return albums.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.music_grid, null);
}
Album album = albums.get(position);
String newString = album.getArtworkURL().replace("100x100", "600x600");
LoaderImageView thumb = (LoaderImageView) convertView.findViewById(R.id.grid_item_image);
thumb.setImageDrawable(newString);
return convertView;
}
}
activity_music.xml
<?xml version="1.0" encoding="utf-8"?>
<com.pixelperfect.mayday.AlbumGridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="150dp"
android:stretchMode="columnWidth"
android:id="#+id/gridView1"/>
music_grid.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:padding="0dp" >
<com.pixelperfect.mayday.LoaderImageView
android:id="#+id/grid_item_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:focusable="false"
android:clickable="false"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher"
android:layout_marginBottom="4dp" />
</LinearLayout>
Main Activity
public class Music extends Activity implements AlbumClickListener {
private AlbumGridView gridView;
// Album[] Album;
private ProgressDialog m_ProgressDialog = null;
#SuppressLint("HandlerLeak")
#Override protected void onResume()
{
super.onResume(); // setText() here
responseHandler = new Handler() {
public void handleMessage(Message msg) {
populateGridWithAlbums(msg);
};
};
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
gridView = (AlbumGridView) findViewById(R.id.gridView1);
gridView.setOnAlbumClickListener(this);
new Thread(new GetAlbumsFromiTunesTask(responseHandler, "GrabTheAlbums", "1")).start();
m_ProgressDialog = ProgressDialog.show(this, "Please wait...", "Loading Albums ...", true);
}
// This is the handler that receives the response when the YouTube task has finished
#SuppressLint("HandlerLeak")
Handler responseHandler = new Handler() {
public void handleMessage(Message msg) {
populateGridWithAlbums(msg);
m_ProgressDialog.dismiss();
};
};
/**
* This method retrieves the Library of videos from the task and passes them to our ListView
* #param msg
*/
private void populateGridWithAlbums(Message msg) {
#SuppressWarnings("unchecked")
List<Album> albums = (List<Album>) (msg.getData().get(GetAlbumsFromiTunesTask.LIBRARY));
gridView.setAdapter(new MusicGridAdapter(this, albums));
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
m_ProgressDialog.dismiss();
}
#Override
public void onAlbumClicked(Album album) {
System.out.println("CLICKED 2");
}
}
I think it would be easier to simply attach an onItemClickListener to your GridView like this:
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> gridView, View view,
int pos, long id) {
//do something -- you can simply use the pos parameter to indicate which element was clicked
}
});