The mainactivity contains navigation drawer. When I click on the navigation drawer tabs, the respective fragment will be opened and in that fragment in Homefragment I want to add ViewPager.
I have added ViewPager in HomeFragment but it is not scrolling horizontally.
This is mainActivity:
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private Toolbar toolbar;
private FloatingActionButton fab;
public static int navItemIndex = 0;
private static final String TAG_HOME = "home";
private static final String TAG_PHOTOS = "photos";
private static final String TAG_MOVIES = "movies";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
private void loadNavHeader() {
// showing dot next to notifications label
navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot);
}
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
drawer.closeDrawers();
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
PhotosFragment photosFragment = new PhotosFragment();
return photosFragment;
case 2:
MoviesFragment moviesFragment = new MoviesFragment();
return moviesFragment;
case 3:
NotificationsFragment notificationsFragment = new NotificationsFragment();
return notificationsFragment;
case 4:
SettingsFragment settingsFragment = new SettingsFragment();
return settingsFragment;
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.nav_photos:
navItemIndex = 1;
CURRENT_TAG = TAG_PHOTOS;
break;
case R.id.nav_movies:
navItemIndex = 2;
CURRENT_TAG = TAG_MOVIES;
break;
case R.id.nav_service_message:
navItemIndex = 3;
CURRENT_TAG = TAG_NOTIFICATIONS;
break;
case R.id.nav_settings:
navItemIndex = 4;
CURRENT_TAG = TAG_SETTINGS;
break;
case R.id.nav_about_us:
startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_privacy_policy:
startActivity(new Intent(MainActivity.this, PrivacyPolicyActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
if (shouldLoadHomeFragOnBackPress) {
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, menu);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
}
This is HomeFragment:
public class HomeFragment extends Fragment {
public HomeFragment() {
}
View view;
ViewPager viewPager;
PagerAdapter adapter;
String[] rank;
String[] country;
String[] population;
int[] flag;
public PageIndicator mIndicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "1,354,040,000", "1,210,193,422",
"315,761,000", "237,641,326", "193,946,886", "182,912,000",
"170,901,000", "152,518,015", "143,369,806", "127,360,000" };
flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria,
R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mIndicator = (PageIndicator) view.findViewById(R.id.pagerIndicator);
viewPager = (ViewPager) view.findViewById(R.id.pager);
adapter = new ViewPagerAdapter(getActivity(), rank, country, population, flag);
viewPager.setAdapter(adapter);
mIndicator.setViewPager(viewPager);
}
}
This is adapter-
public class ViewPagerAdapter extends PagerAdapter {
Context context;
String[] rank;
String[] country;
String[] population;
int[] flag;
LayoutInflater inflater;
public ViewPagerAdapter(Context context, String[] rank, String[] country,
String[] population, int[] flag) {
this.context = context;
this.rank = rank;
this.country = country;
this.population = population;
this.flag = flag;
}
#Override
public int getCount() {
return rank.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
txtrank = (TextView) itemView.findViewById(R.id.rank);
txtcountry = (TextView) itemView.findViewById(R.id.country);
txtpopulation = (TextView) itemView.findViewById(R.id.population);
txtrank.setText(rank[position]);
txtcountry.setText(country[position]);
txtpopulation.setText(population[position]);
// Locate the ImageView in viewpager_item.xml
imgflag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set to the ImageView
imgflag.setImageResource(flag[position]);
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Related
Hello I am newbie in java programming(android). Currently I learn recyclerview use volley in fragments and need help. why when switching fragment one to fragment two and when back to fragment one, recycleview lost? even though at the beginning recyleview available? thanks for help
this is backgroundtask.java
Context mContext;
ArrayList<List> mArrayList = new ArrayList<>();
String json_url = "http://192.168.43.215/belajar/contact_mad.php";
private static final String TAG = "BackgroundTask";
public BackgroundTask(Context context) {
this.mContext = context;
}
public ArrayList<List> getList()
{
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url, (String) null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
int count = 0;
while (count<response.length())
{
try {
JSONObject jsonObject = response.getJSONObject(count);
List list = new List(jsonObject.getString("Id"),jsonObject.getString("ImageUrl"),jsonObject.getString("Name"));
mArrayList.add(list);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mContext,"Errorr.............",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}
);
MySingleton.getInstance(mContext).addToRequestQue(jsonArrayRequest);
Log.e(TAG, "Log Dari background");
return mArrayList;
}
this is recycleradapter.java
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
ArrayList<List> mArrayList = new ArrayList<>();
private static final String TAG = "RecyclerAdapter";
public RecyclerAdapter(ArrayList<List> arrayList){
this.mArrayList = arrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final String name = mTxtName.getText().toString();
final String email = mTxtEmail.getText().toString();
final String nameFood = this.mArrayList.get(position).getName();
final String imageUrl = this.mArrayList.get(position).getImageUrl();
holder.Name.setText(mArrayList.get(position).getName());
final Context context = holder.mImageView.getContext();
Picasso.with(context).load(mArrayList.get(position).getImageUrl()).into(holder.mImageView);
Log.e(TAG, "Log Dari On BindView");
holder.cvMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Intent intent = new Intent(v.getContext(),ActivityClick.class);
Bundle bundle = new Bundle();
bundle.putString("imageUrl",imageUrl);
bundle.putString("name",name);
intent.putExtras(bundle);
v.getContext().startActivity(intent);*/
Toast.makeText(context, name, Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return mArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView Name;
RelativeLayout cvMain;
ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = (ImageView) itemView.findViewById(R.id.imageView);
Name = (TextView)itemView.findViewById(R.id.txtName);
cvMain = (RelativeLayout) itemView.findViewById(R.id.cvMain);
}
}
this is MainMenu.java
public class MainMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static TextView mTxtName, mTxtEmail;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mTxtName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavName);
mTxtEmail = (TextView)navigationView.getHeaderView(0).findViewById(R.id.txtNavEmail);
Bundle bundle = getIntent().getExtras();
mTxtName.setText(bundle.getString("name"));
mTxtEmail.setText(bundle.getString("email"));
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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, 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.cara_pesan) {
return true;
}else if(id == R.id.keluar){
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fm.beginTransaction();
if (id == R.id.list_makanan) {
transaction.replace(R.id.tempatfragment, new ListMakanan()).addToBackStack(null).commit();
} else if (id == R.id.pesan_makanan) {
transaction.replace(R.id.tempatfragment, new PesanMakanan()).addToBackStack(null).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
this is fragment ListMakanan.java
public class ListMakanan extends Fragment {
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
ArrayList<List> mArrayList = new ArrayList<>();
private static final String TAG = "ListMakanan";
public ListMakanan() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_list__makanan, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView = (RecyclerView)view.findViewById(R.id.recyclervView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
BackgroundTask backgroundTask = new BackgroundTask(getActivity());
mArrayList = backgroundTask.getList();
mAdapter = new RecyclerAdapter(mArrayList);
mRecyclerView.setAdapter(mAdapter);
Log.e(TAG, "Log Dari View Created");
}
Whenever you use replace on your FragmentManager to switch fragments you are doing a remove(remove any fragments from container) followed by an add(the new fragment). This wipes out the state of the previous fragment and forces a refresh when you go back, to avoid this you can just call add fragment instead of replace.
I am using DrawerLayoutmenu with a ViewPager and recycleView in my application and I have three tabs in it. I am using ViewPager and recycleView inside a fragment. Now my problem here is, the first time there is no error and when i come back fragment CongThucFragment It looks like it was error
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences sharedPreferencesToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferencesToken=getSharedPreferences("DataChefy",Context.MODE_PRIVATE);
TokenClass.Token = sharedPreferencesToken.getString("Token","");
Log.d("MainActivity10",TokenClass.Token);
if (savedInstanceState == null) {
Fragment fragment = null;
Class fragmentClass = null;
fragmentClass = UserInfoFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
}
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
int id = item.getItemId();
Class fragmentClass = null;
if (id == R.id.nav_camera) {
fragmentClass = UserInfoFragment.class;
try {
ft.replace(R.id.fragment_container,(Fragment) fragmentClass.newInstance(), "UserInfoFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
fragmentClass = CongThucFragment.class;
try {
ft.replace(R.id.fragment_container,(Fragment) fragmentClass.newInstance(), "CongThucFragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else if (id == R.id.nav_manage) {
SharedPreferences.Editor editor = sharedPreferencesToken.edit();
editor.putString("Token","");
editor.apply();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
this.finish();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}}
and this my fragment
public class CongThucFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentActivity myContext;
static public CongThucFragment newInstance(){
return new CongThucFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
myContext = (FragmentActivity) context;
setRetainInstance(true);
super.onAttach(context);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmen_congthuc,container,false);
tabLayout= (TabLayout) view.findViewById(R.id.tabsChampionDetail);
viewPager= (ViewPager) view.findViewById(R.id.viewpagerChampionDetail);
tabLayout.setupWithViewPager(viewPager);
setupViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager ) {
ViewPagerAdapter adapter = new ViewPagerAdapter(myContext.getSupportFragmentManager());
for(int i =1 ;i<=3.;i++) {
if(i==1)adapter.addFragment(ChildrenCongthucFragment.newInstance("vn"), "Country " + i + "");
else if(i==2)adapter.addFragment(ChildrenCongthucFragment.newInstance("lao"), "Country " + i + "");
else adapter.addFragment(ChildrenCongthucFragment.newInstance("tay"), "Country " + i + "");
}
viewPager.setAdapter(adapter);
}}
fragment 2
public class ChildrenCongthucFragment extends Fragment{
String Country = null;
List<Congthuc> mItems = new ArrayList<>();
private RecyclerView mRecyclerView;
private RecyclerDataAdapter recyclerDataAdapter = null;
RecyclerView.LayoutManager layoutManagerNews;
static public ChildrenCongthucFragment newInstance(String country){
Bundle bundle = new Bundle();
bundle.putString("mCountry",country);
ChildrenCongthucFragment fragment = new ChildrenCongthucFragment();
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeData();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycle_children_congthuc,container,false);
Country = getArguments().getString("mCountry");
mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_photo_collection_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerDataAdapter =new RecyclerDataAdapter (view.getContext(),R.layout.recycle_children_congthuc,CountryFillter(Country,mItems));
mRecyclerView.setAdapter(recyclerDataAdapter);
return view;
}
private void initializeData(){
mItems.add(new Congthuc("1", "banh mì","vn","http://giadinh.vcmedia.vn/k:2016/photo-0-1472785146823/nhungmonanngonchogiadinhdip29.jpg"));
mItems.add(new Congthuc("2", "bánh gián","vn","http://toinayangi.vn/wp-content/uploads/2015/06/m%C3%B3n-%C4%83n-vi%E1%BB%87t-nam-n%E1%BB%95i-ti%E1%BA%BFng-g%E1%BB%8Fi-cu%E1%BB%91n.jpg"));
mItems.add(new Congthuc("3", "bún","lao", "http://anh.eva.vn/upload/2-2016/images/2016-06-12/5-mon-an-ngon-tuyet-cho-cuoi-tuan-5-1465696055-width640height80.jpg"));
mItems.add(new Congthuc("4", "phỏ", "lao","https://i0.wp.com/theboola.com/wp-content/uploads/2014/09/144837125.jpg?resize=506%2C341"));
mItems.add(new Congthuc("5", "hủ tíu","tay", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_AWhsxDkMDqkIhPGSNLZj8TFAkF3pedEa6Tt-l72mSt6PdRXaEg"));
mItems.add(new Congthuc("6", "cam","tay", "https://i.imgur.com/3M37NQM.jpg"));
mItems.add(new Congthuc("7", "quýt","ta", "http://vnngon.com/wp-content/uploads/2016/01/cach-lam-mon-an-ngon-ga-nhoi-thap-cam-xoi-vnngon-2.jpg"));
}ArrayList<Congthuc> CountryFillter(String con,List<Congthuc> cts){
List<Congthuc> Ncts = new ArrayList<>();
for (int i = 0;i<cts.size();i++)
{
Congthuc ct = cts.get(i);
if (con.equals(ct.getQuocGia()))
{
Ncts.add(ct);
}
}
return (ArrayList<Congthuc>) Ncts;}}
my adapter
public class RecyclerDataAdapter extends RecyclerView.Adapter<RecyclerDataAdapter.ViewHolder> {
private List<Congthuc> congthucs;
private int layout;
private Context context;
public RecyclerDataAdapter(Context context, int layout, List<Congthuc> congthucs) {
this.context = context;
this.layout=layout;
this.congthucs = congthucs;
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imgCT;
TextView txtCT;
public ViewHolder(View itemView) {
super(itemView);
imgCT= (ImageView) itemView.findViewById(R.id.fragment_image_View);
txtCT= (TextView) itemView.findViewById(R.id.txtDes);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_collection, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Congthuc congthuc = congthucs.get(position);
holder.txtCT.setText(congthuc.getDescription());
Picasso.with(context)
.load(congthuc.getLink())
.placeholder(R.drawable.loader)
.error(R.drawable.placeholder)
.resize(150,120)
.centerCrop()
.skipMemoryCache()
.into(holder.imgCT);
}
#Override
public int getItemCount() {
return congthucs ==null?0:congthucs.size();
}}
I have really browsed through stackoverflow for this solution.
Im trying to access a fragment from another fragment and an error is thrown that
java.lang.ClassCastException: com.noel.myapplication99.IncomeTax cannot be cast to com.noel.myapplication99.IncomeDialog
at com.noel.myapplication99.MainActivity.createOutput(MainActivity.java:119)
at com.noel.myapplication99.IncomeTax$1.onClick(IncomeTax.java:77)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
These are my codes
MainActivity.java
public class MainActivity extends AppCompatActivity
implements IncomeTax.OnFragmentInteractionListener, ResidentialIncomeTax.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, IncomeTax.IncomeTaxListener {
public void onFragmentInteraction(Uri uri){
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment=null;
switch(position)
{
case 0:
fragment = new IncomeTax();
mTitle = getString(R.string.title_section1);
break;
case 1:
fragment = new ResidentialIncomeTax();
mTitle = getString(R.string.title_section2);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment, "Tag").commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void createOutput(int i, int f) {
IncomeDialog incomeDialog = (IncomeDialog) getSupportFragmentManager().findFragmentByTag("Tag");
incomeDialog.setOutputText(i, f);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
IncomeTax.java
public class IncomeTax extends Fragment implements AdapterView.OnItemSelectedListener {
IncomeTaxListener activityCommander;
float selectedIncomeType;
public interface IncomeTaxListener{
public void createOutput(int i, int f);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (IncomeTaxListener) context;
}catch(Exception e){
throw new ClassCastException(toString());
}
}
private OnFragmentInteractionListener mListener;
public IncomeTax() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
Button btnIcCalc;
EditText salary, insuaranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_tax, container, false);
salary = (EditText) view.findViewById(R.id.tvSalary);
insuaranceRelief = (EditText) view.findViewById(R.id.tvReliefCalc);
btnIcCalc = (Button)view.findViewById(R.id.btnIcCalc);
final int iSalary=0;
final int iInsuranceRelief=1;
btnIcCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog box here
activityCommander.createOutput(iSalary, iInsuranceRelief);
FragmentManager manager = getActivity().getSupportFragmentManager();
IncomeDialog myDialog = new IncomeDialog();
myDialog.setTargetFragment(IncomeTax.this, 0);
myDialog.show(manager, "IncomeDialog");
}
});
setSpinnerContent(view);
return view;
}
private void setSpinnerContent( View view )
{
Spinner spinner = (Spinner) view.findViewById( R.id.incomeTypeSpinner );
ArrayAdapter incomeSpinnerArrayAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.income_type_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(incomeSpinnerArrayAdapter );
spinner.setOnItemSelectedListener(this);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
selectedIncomeType = 1;
break;
case 1:
selectedIncomeType = 1;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
IncomeDialog.java
public class IncomeDialog extends DialogFragment {
public IncomeDialog() {
// Required empty public constructor
}
TextView netPay, insuranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
return view;
}
public void setOutputText(int i, int f){
netPay.setText(i);
insuranceRelief.setText(f);
}
If you want to send data to DialogFragmet then try like this:
Bundle bundle = new Bundle();
bundle.putInt("key1", i);
bundle.putInt("key2", f);
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setArguments(bundle);
Now carry out FragmentTransaction to add this incomeDialog. That will show the dialog.
To receive the bundle data in IncomeDialog:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
Bundle bundle=getArguments();
int i = bundle.getInt("key1");
int f = bundle.getInt("key2");
return view;
}
I am new to java and I got an error that couldn't fix.
My app is using the navigation drawer and when I open it the app gets really slow and the logcat displays the message of frame skipping and The application may be doing too much work on its main thread...
Don't know what to do to fix it.
This is part of the code where the drawer is called.
public class MainActivity extends SwipeRefreshActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private View mPanelMenu;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
private Menu[] MENUS;
public static Location location;
public static List<Address> address;
public static int offsetY = 0;
private static SQLiteDatabase db;
private static DbHelper dbHelper;
private static Queries q;
protected static ImageLoader imageLoader;
private static boolean isShownSplash = false;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
// Handle to SharedPreferences for this app
SharedPreferences mPrefs;
// Handle to a SharedPreferences editor
SharedPreferences.Editor mEditor;
private Fragment currFragment;
private GetAddressTask getAddressTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
this.getActionBar().setIcon(R.drawable.header_logo);
this.getActionBar().setTitle("");
dbHelper = new DbHelper(this);
q = new Queries(db, dbHelper);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(getBaseContext()));
statusCallback = new SessionStatusCallback();
mTwitter = new TwitterApp(this, twitterAppListener);
mTitle = mDrawerTitle = "";
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mPanelMenu = findViewById(R.id.panel_slidermenu);
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
mDrawerList.setDividerHeight(0);
updateMenuList();
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu, // nav
// menu
// toggle
// icon
R.string.no_name, // nav drawer open - description for
// accessibility
R.string.no_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
offsetY = TypedValue.complexToDimensionPixelSize(tv.data,
getResources().getDisplayMetrics());
}
if (!isShownSplash) {
isShownSplash = true;
this.getActionBar().hide();
FragmentManager fragmentManager = this.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, new SplashFragment())
.commit();
}
else if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(1);
}
mUpdatesRequested = false;
// Open Shared Preferences
mPrefs = getSharedPreferences(LocationUtils.SHARED_PREFERENCES,
Context.MODE_PRIVATE);
// Get an editor
mEditor = mPrefs.edit();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
FrameLayout frameAds = (FrameLayout) findViewById(R.id.frameAds);
frameAds.setVisibility(View.GONE);
if (MGUtilities.hasConnection(this)) {
q.deleteTable("stores");
q.deleteTable("categories");
q.deleteTable("photos");
q.deleteTable("reviews");
q.deleteTable("ratings");
q.deleteTable("news");
}
}
public void showMainView() {
getActionBar().show();
displayView(1);
showAds();
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
updateMenuList();
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
// case R.id.action_settings:
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public boolean onPrepareOptionsMenu(android.view.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);
}
private void displayView(int position) {
// clear back stack
FragmentManager fm = this.getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new CategoryFragment();
break;
case 3:
fragment = new FavoriteFragment();
break;
case 4:
fragment = new FeaturedFragment();
break;
case 5:
fragment = new MapFragment();
break;
case 6:
fragment = new SearchFragment();
break;
case 7:
fragment = new NewsFragment();
break;
case 8:
fragment = new WeatherFragment();
break;
case 10:
fragment = new AboutUsFragment();
break;
case 11:
fragment = new TermsConditionFragment();
break;
case 13:
UserAccessSession session = UserAccessSession.getInstance(this);
if (session.getUserSession() == null) {
Intent i = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(i);
} else {
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
}
break;
case 14:
Intent i = new Intent(this, LoginActivity.class);
this.startActivity(i);
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
// setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mPanelMenu);
if (currFragment != null && fragment != null) {
boolean result = fragment.getClass()
.equals(currFragment.getClass());
if (result)
return;
}
if (fragment != null) {
if (fragment instanceof MapFragment) {
currFragment = fragment;
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
FragmentManager fragmentManager = MainActivity.this
.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, currFragment)
.commit();
}
}, Config.DELAY_SHOW_ANIMATION + 200);
} else {
currFragment = fragment;
FragmentManager fragmentManager = this
.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().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);
}
public void updateMenuList() {
UserAccessSession accessSession = UserAccessSession.getInstance(this);
UserSession userSession = accessSession.getUserSession();
if (userSession == null) {
MENUS = UIConfig.MENUS_NOT_LOGGED;
} else {
MENUS = UIConfig.MENUS_LOGGED;
}
showList();
}
public void showList() {
MGListAdapter adapter = new MGListAdapter(this, MENUS.length,
R.layout.menu_entry);
adapter.setOnMGListAdapterAdapterListener(new OnMGListAdapterAdapterListener() {
#Override
public void OnMGListAdapterAdapterCreated(MGListAdapter adapter,
View v, int position, ViewGroup viewGroup) {
// TODO Auto-generated method stub
FrameLayout frameCategory = (FrameLayout) v
.findViewById(R.id.frameCategory);
View frameHeader = v.findViewById(R.id.frameHeader);
frameCategory.setVisibility(View.GONE);
frameHeader.setVisibility(View.GONE);
Menu menu = MENUS[position];
if (menu.getHeaderType() == HeaderType.HeaderType_CATEGORY) {
frameCategory.setVisibility(View.VISIBLE);
Spanned title = Html.fromHtml(MainActivity.this
.getResources().getString(menu.getMenuResTitle()));
TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
tvTitle.setText(title);
ImageView imgViewIcon = (ImageView) v
.findViewById(R.id.imgViewIcon);
imgViewIcon.setImageResource(menu.getMenuResIconSelected());
} else {
frameHeader.setVisibility(View.VISIBLE);
Spanned title = Html.fromHtml(MainActivity.this
.getResources().getString(menu.getMenuResTitle()));
TextView tvTitleHeader = (TextView) v
.findViewById(R.id.tvTitleHeader);
tvTitleHeader.setText(title);
}
}
});
mDrawerList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
Below is the adapter code
public class MGListAdapter extends BaseAdapter {
Context c;
private int count;
private int resId;
OnMGListAdapterAdapterListener mCallback;
#SuppressWarnings("unused")
private int mLastPosition = 1;
public interface OnMGListAdapterAdapterListener {
public void OnMGListAdapterAdapterCreated(MGListAdapter
adapter, View v, int position, ViewGroup viewGroup);
}
public void setOnMGListAdapterAdapterListener(OnMGListAdapterAdapterListener listener) {
try {
mCallback = (OnMGListAdapterAdapterListener) listener;
} catch (ClassCastException e) {
throw new ClassCastException(this.toString() + " must implement OnMGListAdapterAdapterListener");
}
}
public MGListAdapter(Context c, int count, int resId) {
this.c = c;
this.count = count;
this.resId = resId;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
return pos;
}
#Override
public View getView(int pos, View v, ViewGroup viewGroup) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
if(v == null) {
LayoutInflater li = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(resId, null);
viewHolder = new ViewHolder();
viewHolder.view = v;
v.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) v.getTag();
Log.w("MGListAdapter Class", "View being reused.");
}
if(mCallback != null)
mCallback.OnMGListAdapterAdapterCreated(this, viewHolder.view, pos, viewGroup);
return v;
}
public class ViewHolder {
public View view;
}
}
Ok guys, I found my error, it was a really stupid error on my side...
At the drawable folder I forgot to resize the menu's icons, it was at 500px, now that I have resized all the icons the Drawer Menu is normal again, no warning messages.
Thanks #Sheychan, #Gaurav and #nmio for the efforts.
I'm getting error stating "mImages & stringArray cannot be resolved to a variable" however I'm unsure why. I have used the following example and I'm pretty sure I've followed it very closely.
Different text for each image in image viewpager
ERROR LOCATIONS:
mImages cannot be resolved to a variable:
ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages, stringArray);
stringArray cannot be resolved to a variable:
uploader.setText(stringArray[position]);
SOURCE: Home.java
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 = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
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(this, mImages, stringArray);
#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
PLAYLIST.replace("TimMcGrawVEVO", PLAYLIST);
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
PLAYLIST.replace("TimMcGrawVEVO", PLAYLIST);
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
}
});
}
}
}
SOURCE: VideosAdapter
public class VideosAdapter extends BaseAdapter {
// The list of videos to display
List<Video> videos;
// An inflator to use when creating rows
private LayoutInflater mInflater;
Button fav_up_btn1;
Button fav_dwn_btn1;
Context my_context;
/**
* #param context this is the context that the list will be shown in - used to create new list rows
* #param videos this is a list of videos to display
*/
public VideosAdapter(Context context, List<Video> videos) {
this.videos = videos;
this.mInflater = LayoutInflater.from(context);
my_context = context;
}
#Override
public int getCount() {
return videos.size();
}
#Override
public Object getItem(int position) {
return videos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our list_item_user_video so no need to do it again
if(convertView == null){
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video, parent, false);
}
// We are using a custom imageview so that we can load images using urls
// For further explanation see: http://blog.blundell-apps.com/imageview-with-loading-spinner/
UrlImageView thumb = (UrlImageView) convertView.findViewById(R.id.userVideoThumbImageView);
TextView title = (TextView) convertView.findViewById(R.id.userVideoTitleTextView);
TextView uploader = (TextView) convertView.findViewById(R.id.userVideouploaderTextView);
// TextView uploader = (TextView) layout.findViewById(R.id.userVideouploaderTextView);
uploader.setText(stringArray[position]);
fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
fav_up_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean favIsUp = fav_up_btn1
.getBackground()
.getConstantState()
.equals(my_context.getResources().getDrawable(
R.drawable.fav_up_btn1).getConstantState());
// set the background
fav_up_btn1
.setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
: R.drawable.fav_up_btn1);
}
});
// Get a single video from our list
final Video video = videos.get(position);
// Set the image for the list item
thumb.setImageDrawable(video.getThumbUrl());
// Set the title for the list item
title.setText(video.getTitle());
uploader.setText("by " + video.getUploader() + " | ");
return convertView;
}
}
You don't have a stringarray, you have videos in VideoAdapter.java. So you should do something like uploader.setText(videos.get(position).getTitle())