How to add a new set of items in a sliding menu? - android

I want to add another block, or set, or whatever it is called, of items in my sliding menu but I can't figure out what to change to the code of the first... In my sliding menu I have 6 items, but I to have 4 items to the first title, and then, another title, and another 2 items.. but i can't figure out what do I have to change to my first block code.. Thanks a lot !!!!
Here is my MainActivity.java:
package com.orar.cngcnasaud;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
private static final String TAG = "AudioDemo";
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
MediaPlayer player;
Button playerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
player = MediaPlayer.create(this, R.raw.gc);
player.setLooping(false); // Set looping
// Get the button from the view
playerButton = (Button) this.findViewById(R.id.buttonmp);
playerButton.setText(R.string.play_label);
playerButton.setTextColor(Color.WHITE);
playerButton.setOnClickListener((OnClickListener) this);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
public void onClick(View v) {
Log.d(TAG, "onClick: " + v);
if (v.getId() == R.id.buttonmp) {
playPause();
}
}
private void demoPause() {
// TODO Auto-generated method stub
player.pause();
playerButton.setText(R.string.play_label);
Log.d(TAG, notPlaying);
}
private void playPause() {
// TODO Auto-generated method stub
if(player.isPlaying()) {
demoPause();
} else {
demoPlay();
}
}
private void demoPlay() {
// TODO Auto-generated method stub
player.start();
playerButton.setText(R.string.stop_label);
Log.d(TAG, isPlaying);
}
private 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);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
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 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) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(MainActivity.this, Istoric.class);
startActivity(intent);
mDrawer.closeDrawers();
}
else if (position == 2) {
Intent intent2 = new Intent(MainActivity.this, Profesori.class);
startActivity(intent2);
mDrawer.closeDrawers();
}
if (position == 3) {
Intent intent3 = new Intent(MainActivity.this, Elevi.class);
startActivity(intent3);
mDrawer.closeDrawers();
}
if (position == 4) {
Intent intent4 = new Intent(MainActivity.this, ShowImageActivity.class);
startActivity(intent4);
mDrawer.closeDrawers();
}
if (position == 5) {
Intent intent5 = new Intent(MainActivity.this, Despre.class);
startActivity(intent5);
mDrawer.closeDrawers();
}
if (position == 6) {
Intent intent6 = new Intent(MainActivity.this, Feedback.class);
startActivity(intent6);
mDrawer.closeDrawers();
}
}
}
}
Thanks again !

I assume you want to achieve something similar to what is in the following picture:
You will have to modify your list adapter(NsMenuAdapter) to support two types of view - item and title where item is clickable and title is just kind of group header. Adapter should takes array/list of objects and every object should have type attribute. This will probably complicate a little OnItemClickListener.
I'm posting my example of that kind list adapter. In my case I created NavigationDrawerItem model to hold information about item type, item 'clickability' and what action should be triggered after item get clicked.
public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItem> {
private static final String TAG = "NavigationDrawerAdapter";
public NavigationDrawerAdapter(Context context, int resource, NavigationDrawerItem[] objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (null == convertView) {
int itemType = getItemViewType(position);
if (NavigationDrawerItem.TYPE_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
} else if (NavigationDrawerItem.TYPE_ITEM_UNDER_TITLE == itemType) {
convertView = View.inflate(getContext(), R.layout.item_under_title_navigation_drawer, null);
} else {
Log.e(TAG, "Returning default title view - Invalid drawer item type" + itemType);
convertView = View.inflate(getContext(), R.layout.item_title_navigation_drawer, null);
}
}
TextView tv = (TextView) convertView.findViewById(R.id.text);
tv.setText(getContext().getString(getItem(position).stringRes));
return convertView;
}
#Override
public int getItemViewType(int position) {
return getItem(position).type;
}
#Override
public int getViewTypeCount() {
return NavigationDrawerItem.NUMBER_OF_ITEM_TYPES;
}
#Override
public boolean isEnabled(int position) {
return NavigationDrawerItem.isItemClickable(getItemViewType(position));
}
}
And the NavigationDrawerItem class:
public final class NavigationDrawerItem {
private static final String TAG = "NavigationDrawerItem";
// Types must have numbers from 0 to n without gaps.
public static final int TYPE_TITLE = 0;// nonclickable
public static final int TYPE_ITEM_UNDER_TITLE = 1;// clickabel
public static final int NUMBER_OF_ITEM_TYPES = 2;
public final int action;
public final String argument;
public final int type;
//Constructors etc.
public static final boolean isItemClickable(int itemType) {
if (TYPE_TITLE == itemType) {
return false;
} else if (TYPE_ITEM_UNDER_TITLE == itemType) {
return true;
} else {
Log.e(TAG, "Invalid item type " + itemType);
return false;
}
}
}

Related

RecyclerView datas last row display with multiple time

I don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())

Spinner: AppCompatSpinner cannot be cast to com.example.....MySpinner (Android)

I am trying to trigger an event from same item selected from the spinner. I found class called MySpinner that extends Spinner but obviously i have problems with its implementation.
package com.example.ilija.festivalapp_makedox;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ilija.festivalapp_makedox.MySpinner;
import com.example.ilija.festivalapp_makedox.agendacalendarview.CalendarPickerController;
import java.util.ArrayList;
public class CustomSpinner extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
public ArrayList<SpinnerModel> CustomListViewValuesArr=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr1=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr2=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr3=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArrTest=new ArrayList<>();
/*public ArrayList<SpinnerModel> CustomListViewValuesArr1Test=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr2Test=new ArrayList<>();
public ArrayList<SpinnerModel> CustomListViewValuesArr3Test=new ArrayList<>();*/
TextView output = null;
CustomSpinner activity = null;
NavigationView navigationView;
CustomAdapter adapter,adapter1,adapter2,adapter3,adapterTest,adapter1Test,adapter2Test,adapter3Test;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_spinner);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Movies");
setSupportActionBar(toolbar);
activity = this;
Spinner SpinnerExample = (Spinner) findViewById(R.id.spinner);
Spinner SpinnerExample1 = (Spinner) findViewById(R.id.spinner1);
Spinner SpinnerExample2 = (Spinner) findViewById(R.id.spinner2);
Spinner SpinnerExample3 = (Spinner) findViewById(R.id.spinner3);
MySpinner SpinnerExampleTest = (MySpinner) findViewById(R.id.spinnerTest);
/* Spinner SpinnerExampleTest = (Spinner) findViewById(R.id.spinnerTest);
Spinner SpinnerExampleTest1 = (Spinner) findViewById(R.id.spinner1Test);
Spinner SpinnerExampleTest2 = (Spinner) findViewById(R.id.spinner2Test);
Spinner SpinnerExampleTest3 = (Spinner) findViewById(R.id.spinner3Test);*/
output = (TextView)findViewById(R.id.output);
setListData();
setListData1();
setListData2();
setListData3();
setListDataTest();
/* setListData1Test();
setListData2Test();
setListData3Test();*/
Resources res = getResources();
adapter = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr,res);
adapter1 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr1,res);
adapter2 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr2,res);
adapter3 = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr3,res);
adapterTest = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArrTest,res);
/* adapter1Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr1Test,res);
adapter2Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr2Test,res);
adapter3Test = new CustomAdapter(activity,R.layout.spinner_rows,CustomListViewValuesArr3Test,res);*/
SpinnerExample.setAdapter(adapter);
SpinnerExample.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>1){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExample1.setAdapter(adapter1);
SpinnerExample1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>2){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExample2.setAdapter(adapter2);
SpinnerExample2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "HERE" , Toast.LENGTH_SHORT).show();
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>3){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView arg0) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE AGAIN", Toast.LENGTH_SHORT).show();
}
});
SpinnerExample3.setAdapter(adapter3);
SpinnerExample3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
i++; //Avoid fist time oppening the OnClick start new intent. First time is for set pic of the first element in the list.
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
if(i>4){
Intent intent = new Intent(CustomSpinner.this, MovieTrailer.class);
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//********************************************************TEST COMPONENTS******************************************************************//
SpinnerExampleTest.setAdapter(adapterTest);
SpinnerExampleTest.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE", Toast.LENGTH_SHORT).show();
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(getApplicationContext(), (CharSequence) "HERE AGAIN", Toast.LENGTH_SHORT).show();
}
});
/* SpinnerExampleTest1.setAdapter(adapter1Test);
SpinnerExampleTest1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExampleTest2.setAdapter(adapter2Test);
SpinnerExampleTest2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SpinnerExampleTest3.setAdapter(adapter3Test);
SpinnerExampleTest3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Movie = ((TextView) view.findViewById(R.id.movieName)).getText().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
*/
//**************************************************TEST COMPONENTS**************************************************************************************//
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
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();
}
});*/
}
public void setListData(){
String moy[] = {"DEN UNGE ZLATAN/BECOMING ZLATAN","THE SWEDISH THEORY OF LOVE","JONAS E O CIRCO SEM LONA/JONAS AND THE BACKYARD CIRCUS","ZID SMRTI, I TAKO TO/WALL OF DEATH, AND ALL",
"ПОСЛАННИКИ БОЛЬШОЙ ЗЕМЛИ/ SIBERIAN FLOATING HOSPITAL","FIGURA/FIGURE","1","2","3","1","2","3"};
for(int i=0;i<moy.length;i++){
final SpinnerModel sched = new SpinnerModel();
sched.setMovieName(moy[i]);
sched.setImage("image1"+i);
CustomListViewValuesArr.add(sched);
}
}
public void setListData1(){
String moy1[] = {"EL BOTÓN DE NÁCAR/PEARL","BRØDRE/BROTHERS 2015 110’","V LUCHAKH SOLNCA/UNDER THE SUN","KANTON JUGOSLAWIEN/LITTLE YUGOSLAVIA","1","2","3","1","2","3","1","2","3","1","2","3"};
for(int i=0;i<moy1.length;i++){
final SpinnerModel sched1 = new SpinnerModel();
sched1.setMovieName(moy1[i]);
sched1.setImage("image2"+i);
CustomListViewValuesArr1.add(sched1);
}
}
public void setListData2(){
String moy2[] = {"JUST ANOTHER DAY IN EGYPT","THE PERFECT CIRCLE","MOJ NAROBE SVET/MY WORLD IS UPSIDE DOWN","1","2","3","1","2","3","1","2","3","1","2","3"};
for(int i=0;i<moy2.length;i++){
final SpinnerModel sched2 = new SpinnerModel();
sched2.setMovieName(moy2[i]);
sched2.setImage("image3"+i);
CustomListViewValuesArr2.add(sched2);
}
}
public void setListData3(){
String moy3[] = {"BREZMEJNO/BEYOND BOUNDARIES","SOMETHING ABOUT LIFE","NA KRAYU/ON THE EDGE","JAMEY’S GEVECHT/JAMEY’S FIGHT","SCHWERELOS/ZERO-G"};
for(int i=0;i<moy3.length;i++){
final SpinnerModel sched3 = new SpinnerModel();
sched3.setMovieName(moy3[i]);
sched3.setImage("image4"+i);
CustomListViewValuesArr3.add(sched3);
}
}
//**************************************************TEST COMPONENTS**************************************************************************************//
public void setListDataTest(){
String moyTest[] = {"MovieTest1","MovieTest2","MovieTest2"};
for(int i=0;i<moyTest.length;i++){
final SpinnerModel schedTest = new SpinnerModel();
schedTest.setMovieName(moyTest[i]);
schedTest.setImage("image"+i);
CustomListViewValuesArrTest.add(schedTest);
}
}
/* public void setListData1Test(){
String moy1Test[] = {"MovieTest1","MovieTest1","Movie1","Movie1"};
for(int i=0;i<moy1Test.length;i++){
final SpinnerModel sched1Test = new SpinnerModel();
sched1Test.setMovieName(moy1Test[i]);
sched1Test.setImage("image"+i);
CustomListViewValuesArr1Test.add(sched1Test);
}
}
public void setListData2Test(){
String moy2Test[] = {"MovieTest1","MovieTest2","Movie3"};
for(int i=0;i<moy2Test.length;i++){
final SpinnerModel sched2Test = new SpinnerModel();
sched2Test.setMovieName(moy2Test[i]);
sched2Test.setImage("image"+i);
CustomListViewValuesArr2Test.add(sched2Test);
}
}
public void setListData3Test(){
String moy3Test[] = {"Movie1","Movie2","Movie3"};
for(int i=0;i<moy3Test.length;i++){
final SpinnerModel sched3Test = new SpinnerModel();
sched3Test.setMovieName(moy3Test[i]);
sched3Test.setImage("image"+i);
CustomListViewValuesArr3Test.add(sched3Test);
}
}
*/
//**************************************************TEST COMPONENTS**************************************************************************************//
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
Intent intent = new Intent(CustomSpinner.this, MainScreen.class);
startActivity(intent);
Toast.makeText(getBaseContext(), "Program", Toast.LENGTH_LONG).show();
//Set the fragment initially
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent i = new Intent(CustomSpinner.this, CustomSpinner.class);
startActivity(i);
Toast.makeText(getBaseContext(), "Movies", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_slideshow) {
Intent intent = new Intent(CustomSpinner.this, BasicActivity.class);
startActivity(intent);
Toast.makeText(getBaseContext(), "Timeline", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
//Intent intent = new Intent(MainScreen.this, MapsActivity.class);
// startActivity(intent);
// Toast.makeText(getBaseContext(), "Maps", Toast.LENGTH_LONG).show();
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
the class MySpinner contains this code:
public class MySpinner extends Spinner {
OnItemSelectedListener listener;
public MySpinner(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setSelection(int position) {
super.setSelection(position);
if (listener != null)
listener.onItemSelected(null, null, position, 0);
}
public void setOnItemSelectedEvenIfUnchangedListener(
AdapterView.OnItemSelectedListener listener) {
this.listener = listener;
}
}
When open this Activity i have this error, and app crashes.
/com.example.ilija.festivalapp_makedox E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ilija.festivalapp_makedox, PID: 12914
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ilija.festivalapp_makedox/com.example.ilija.festivalapp_makedox.CustomSpinner}: java.lang.ClassCastException: android.support.v7.widget.AppCompatSpinner cannot be cast to com.example.ilija.festivalapp_makedox.MySpinner
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.support.v7.widget.AppCompatSpinner cannot be cast to com.example.ilija.festivalapp_makedox.MySpinner
at com.example.ilija.festivalapp_makedox.CustomSpinner.onCreate(CustomSpinner.java:56)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653) 
at android.app.ActivityThread.access$800(ActivityThread.java:156) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:157) 
at android.app.ActivityThread.main(ActivityThread.java:5872) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) 
at dalvik.system.NativeStart.main(Native Method) 
I guess that layout.activity_custom_spinner.xml is like this:
<Spinner id="#+id/spinnerTest" ...>
it should be like this:
<MySpinner id="#+id/spinnerTest" ...>
And MySpinner can be extends android.support.v7.widget.AppCompatSpinner.
https://developer.android.com/reference/android/support/v7/widget/AppCompatSpinner.html
This will automatically be used when you use Spinner in your layouts.
You should only need to manually use this class when writing custom
views.

I want a popup in my android

I want a pop like this when i click an item in the list. In the popupmenu i should not be able to increase my height above 7 ft and 0 inch and shouldnt decrease my height below 3 ft and 0 inch.
This is my activity
package com.example.shivnandan.fit;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity1 extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
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);
/////////////////////////////////////////////////////////
listView = (ListView) findViewById(R.id.listView2);
final ListViewItem[] items = new ListViewItem[5];
for (int i = 0; i < items.length; i++)
{
if (i == 0)
{
items[i] = new ListViewItem("White " + i, CustomAdapter.TYPE_WHITE); //mainactivity
}
else if (i == 1)
{
items[i] = new ListViewItem( "Black " + i, CustomAdapter.TYPE_BLACK ); //1
}
else if (i == 2)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_ODD); //2
}
else if (i == 3)
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_EVEN); //3
}
else
{
items[i] = new ListViewItem("EVEN " + i, CustomAdapter.TYPE_FOUR); //4
}
/* else
{
items[i] = new ListViewItem( "odd"+i,CustomAdapter.TYPE_WHITE);
}*/
}
CustomAdapter customAdapter = new CustomAdapter(this, R.id.text, items);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView adapterView, View view, int i, long l)
{
if (i == 0)
{
openDialogManager();
}
}
});
}
public void openDialogManager()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
public void openDialogManagerr()
{
final TextView tv3 = (TextView)findViewById(R.id.hometext);
final CharSequence[] items = {"Male", "Female"};
new AlertDialog.Builder(MainActivity1.this)
.setTitle("Gender")
.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which)
{
case 0:
// Toast.makeText( MainActivity1.this, "male ", Toast.LENGTH_SHORT).show();
tv3.setText("Male");
dialog.dismiss();
break;
case 1:
// Toast.makeText(MainActivity1.this, "female ", Toast.LENGTH_SHORT).show();
tv3.setText("Female");
dialog.dismiss();
break;
}
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
})
.show();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
Toast.makeText(getApplicationContext(), " Setting ", Toast.LENGTH_SHORT).show();
return true;
}
if(id==R.id.Change_photo)
{
Toast.makeText(getApplicationContext(),"Change Your Photo",Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera)
{
}
else if (id == R.id.nav_gallery)
{
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
else if (id == R.id.nav_slideshow)
{
}
else if (id == R.id.nav_manage)
{
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
class ListViewItem
{
private String text;
private int type;
public ListViewItem(String text, int type)
{
this.text = text;
this.type = type;
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
}
class ViewHolder
{
TextView text;
public ViewHolder(TextView text) {
this.text = text;
}
public TextView getText() {
return text;
}
public void setText(TextView text) {
this.text = text;
}
}
class CustomAdapter extends ArrayAdapter
{
public static final int TYPE_ODD = 0;
public static final int TYPE_EVEN = 1;
public static final int TYPE_WHITE = 2;
public static final int TYPE_BLACK = 3;
public static final int TYPE_FOUR = 4;
private ListViewItem[] objects;
#Override
public int getViewTypeCount()
{
return 4;
}
#Override
public int getItemViewType(int position)
{
return objects[position].getType();
}
public CustomAdapter(MainActivity1 context, int resource, ListViewItem[] objects)
{
super(context, resource, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder = null;
ListViewItem listViewItem = objects[position];
int listViewItemType = getItemViewType(position);
if (convertView == null)
{
if (listViewItemType == TYPE_EVEN)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.even, null);
}
else if (listViewItemType == TYPE_ODD)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.odd, null);
}
else if (listViewItemType == TYPE_WHITE)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.white, null);
}
else if (listViewItemType == TYPE_FOUR)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.four, null);
}
else
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.black, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.text);
viewHolder = new ViewHolder(textView);
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
// viewHolder.getText().setText(listViewItem.getText());
return convertView;
}
}
1.Create a custom dialog and adjust to your needs, e. g. my_dialog.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tv_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"/>
<Button
android:id="#+id/btn_dialog"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/tv_dialog"
android:text="Button"/>
</RelativeLayout>
2.Declare and open dialog from activity:
my_dialog = new Dialog(context);
my_dialog .requestWindowFeature(Window.FEATURE_NO_TITLE);
my_dialog .setCancelable(true);
my_dialog .setContentView(R.layout.my_dialog);
my_dialog.show();

Android Recycler layouts not inflating properly why

I use an android recyclerview to inflate three layouts as shown in my code but the footer is not being inflated properly hence hides some data of the listview layout. Where is the problem with my code since I want the listview layout to be displayed as the last layout in the recyclerview adapter.
package com.news254.inception.newsapp;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
public class Newspaper extends AppCompatActivity {
Toolbar mtoolbar;
String TITLES[] = {"Newspaper","Gossip","Entertainment","Sports","International","About","Exit"};
int ICONS[] = {R.drawable.newspaper,R.drawable.gossip,R.drawable.entertainment,R.drawable.sports,R.drawable.international,R.drawable.about,R.drawable.exit};
//Similarly we Create a String Resource for the name and email in the header
view
//And we also create a int resource for profile picture in the header view
Boolean isDrawerOpen =true;
private Toolbar toolbar; // Declaring the
Toolbar Object
RecyclerView mRecyclerView; // Declaring
RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter
For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout
Manager as a linear layout manager
DrawerLayout Drawer; // Declaring
DrawerLayout
ActionBarDrawerToggle mDrawerToggle;
ImageView
Nation,Standard,Capital,Nairobian,BusinessDaily,EastAfrican,Star,Mwakilishi,Citizen;
String nation = "http://www.nation.co.ke";
String standard = "http://www.standardmedia.co.ke";
String star = "http://www.the-star.co.ke";
String nairobian = "http://www.sde.co.ke/m/thenairobian";
String eastafrican = "http://www.theeastafrican.co.ke";
String businessdaily = "http://www.businessdailyafrica.com";
String mwakilishi = "http://www.mwakilishi.com";
String capital = "http://www.capitalfm.co.ke";
String citizen = "http://www.theweeklycitizen.co.ke";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
mtoolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mtoolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES,ICONS); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Nation = (ImageView) findViewById(R.id.nation);
Nation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",nation);
startActivity(p);
}
});
Standard = (ImageView) findViewById(R.id.standard);
Standard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",standard);
startActivity(p);
}
});
Star = (ImageView) findViewById(R.id.star);
Star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Entertainment.class);
p.putExtra("site",star);
startActivity(p);
}
});
Capital = (ImageView) findViewById(R.id.capital);
Capital.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",capital);
startActivity(p);
}
});
Nairobian = (ImageView) findViewById(R.id.nairobian);
Nairobian.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",nairobian);
startActivity(p);
}
});
Citizen = (ImageView) findViewById(R.id.citizen);
Citizen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",citizen);
startActivity(p);
}
});
EastAfrican = (ImageView) findViewById(R.id.eastafrican);
EastAfrican.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",eastafrican);
startActivity(p);
}
});
BusinessDaily = (ImageView) findViewById(R.id.businessdaily);
BusinessDaily.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",businessdaily);
startActivity(p);
}
});
Mwakilishi = (ImageView) findViewById(R.id.mwakilishi);
Mwakilishi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent p = new Intent(Newspaper.this,Browser.class);
p.putExtra("site",mwakilishi);
startActivity(p);
}
});
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
/* #Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if(slideOffset >.55 && !isDrawerOpen)
{
onDrawerOpened(drawerView);
isDrawerOpen=true;
}
else if (slideOffset <.45 && isDrawerOpen)
{
onDrawerClosed(drawerView);
isDrawerOpen = false;
}
// super.onDrawerSlide(drawerView, slideOffset);
}*/
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle);
// / Drawer Listener set to the Drawer toggle
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_news, 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();
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} }
package com.news254.inception.newsapp;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by hp1 on 28-12-2014.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private static final int TYPE_FOOTER = 2; // Declaring Variable to
Understand which View is being worked on
// IF the view under inflation and population is header or Item
private static final int TYPE_ITEM = 1;
private static final int TYPE_HEADER= 0;
private String mNavTitles[]; // String Array to store the passed titles
Value from MainActivity.java
private int mIcons[]; // Int Array to store the passed icons
resource value from MainActivity.java
private int mfooter[];
private String mtitleFoot[];
int Holderid;
// Creating a ViewHolder which extends the RecyclerView View Holder
// ViewHolder are used to to store the inflated views in order to
recycle them
public static class ViewHolder extends RecyclerView.ViewHolder {
int Holderid;
TextView textView;
ImageView imageView;
ImageView about;
TextView name;
public ViewHolder(View itemView,int ViewType) { // Creating ViewHolder Constructor with View and viewType As a parameter
super(itemView);
// Here we set the appropriate view in accordance with the the view type as passed when the holder object is created
if(ViewType == TYPE_ITEM) {
textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
Holderid = 1; // setting holder id as 1 as the object being populated are of type item row
}
else if(ViewType == TYPE_FOOTER){
about = (ImageView) itemView.findViewById(R.id.image); // Creating Text View object from header.xml for name
name = (TextView) itemView.findViewById(R.id.text); // Creating Text View object from header.xml for email
// Creating Image view object from header.xml for profile pic
Holderid =2; // Setting holder id = 0 as the object being populated are of type header view
}
else if(ViewType == TYPE_HEADER)
{
Holderid =0;
}
}
}
MyAdapter(String Titles[],int Icons[]){ // MyAdapter Constructor
with titles and icons parameter
// titles, icons, name, email, profile pic are passed from the
main activity as we
mNavTitles = Titles; //have seen earlier
mIcons = Icons;
//here we assign those passed values to the values
we declared here
//in adapter
}
//Below first we ovverride the method onCreateViewHolder which is called when
the ViewHolder is
//Created, In this method we inflate the item_row.xml layout if the
viewType is Type_ITEM or else we inflate header.xml
// if the viewType is TYPE_HEADER
// and pass it to the view holder
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview,parent,false); //Inflating the layout
ViewHolder vhItem = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view
return vhItem; // Returning the created object
//inflate your layout and pass it to view holder
}
else if (viewType == TYPE_HEADER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false); //Inflating the layout
ViewHolder vhHeader = new ViewHolder(v, viewType); //Creating ViewHolder and passing the object of type view
return vhHeader; //returning the object created
}
else if (viewType == TYPE_FOOTER) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.footer, parent, false); //Inflating the layout
ViewHolder vhHeader = new ViewHolder(v, viewType); //Creating ViewHolder and passing the object of type view
return vhHeader; //returning the object created
}
return null;
}
//Next we override a method which is called when the item in a row is
needed to be displayed, here the int position
// Tells us item at which position is being constructed to be displayed
and the holder id of the holder object tell us
// which view type is being created 1 for item row
#Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int
position) {
if(holder.Holderid ==1) { // as the list view is going to be called after the header view so we decrement the
// position by 1 and pass it to the holder while setting the text and image
holder.textView.setText(mNavTitles[position-2]); // Setting the Text with the array of our Titles
holder.imageView.setImageResource(mIcons[position-2]);// Settimg the image with array of our icons
}
else if (holder.Holderid ==2){
holder.about.setImageResource(mIcons[position]); // Similarly we set the resources for header view
holder.name.setText(mNavTitles[position]);
}
else if (holder.Holderid ==0){
}
}
// This method returns the number of items present in the list
#Override
public int getItemCount() {
return mNavTitles.length+2;
// the number of items in the list will be +1 the titles including the header view.
}
// Witht the following method we check what type of view is being passed
#Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEADER;
}
else if (position ==2) {
return TYPE_FOOTER ;
}
else {
return TYPE_ITEM;
}
}
private boolean isPositionHeader(int position) {
return position == 0;
}
}
Change this
#Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEADER;
}
else if (position ==2) {
return TYPE_FOOTER ;
}
else {
return TYPE_ITEM;
}
}
To
#Override
public int getItemViewType(int position) {
if(position==0){
return TYPE_HEADER;
}
else if((mNavTitles.length+ 1) == position){
return TYPE_FOOTER;
}else{
return TYPE_ITEM;
}
}

How to add image on header in Navigation Drawer

I am using Gabriele Mariotti navigation drawer library to create the sliding menu. It works perfect, but I'm facing with adding an image, as header in it. It should look something like this:
I mean.. not exactly the same, but the idea of having the image as header. Thanks !
MainActivity:
package ro.volunteer;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
public class NewsFeed extends Activity implements OnClickListener {
private ListView mDrawerList;
private DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
menuItems = getResources().getStringArray(
R.array.ns_menu_items_icon);
// 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);
if (res==1) mItem.counter=0; //it is just an example...
if (res==3) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.ns_menu_main_header2);
menuItems = getResources().getStringArray(
R.array.ns_menu_items2);
String[] menuItemsIcon1 = getResources().getStringArray(
R.array.ns_menu_items_icon3);
int res2 = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon1[res2],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res2==1) mItem.counter=0; //it is just an example...
mAdapter.addItem(mItem);
res2++;
}
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 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) {
mDrawerList.setItemChecked(position, true);
mDrawer.closeDrawer(mDrawerList);
if (position == 1) {
Intent intent = new Intent(NewsFeed.this, Profile.class);
startActivity(intent);
mDrawer.closeDrawers();
}
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Adapter:
package ro.volunteer;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
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);
text1.setTextColor(Color.WHITE);
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));
}
if (holder == null && view != null) {
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);
holder.textCounterHolder.setText(""+item.counter);
}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;
}
}
**ItemModel:**
package ro.volunteer;
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);
}
}

Categories

Resources