I am developing an Android application which has a seating plan. The seats are ImageViews placed in the GridView. On click, the imageview will be set to a different image. The problem is no matter which seat I click on, only the first seat's image is changed. Hope to be able to get some help as to why. Following is my code:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
<TextView
android:id="#+id/grid_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="15dp"
android:text="#string/screen"
android:textSize="20sp"
android:gravity="center" >
</TextView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:paddingTop="10dp">
<GridView
android:id="#+id/gridView"
android:layout_width="240dp"
android:layout_height="match_parent"
android:paddingTop="15dp"
android:listSelector="#android:color/transparent"
android:numColumns="8"
android:columnWidth="30dp"
android:gravity="center"
android:verticalSpacing="0dp"
android:stretchMode="none"
android:layout_centerInParent ="true">
</GridView>
</RelativeLayout>
</LinearLayout>
seat_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/seatItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity implements OnItemClickListener {
GridView gridview;
ImageAdapter imageAdapter;
ArrayList<Item> data = new ArrayList<Item>();
ImageView image;
boolean showingFirst = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView(); // Initialize the GUI Components
fillData(); // Insert The Data
setDataAdapter(); // Set the Data Adapter
}
// Initialize the GUI Components
private void initView() {
gridview = (GridView) findViewById(R.id.gridView);
gridview.setOnItemClickListener(this);
}
// Insert The Data
private void fillData() {
for (int i = 1; i < 17; i++) {
data.add(new Item(i, getResources().getDrawable(R.drawable.seat)));
}
}
// Set the Data Adapter
private void setDataAdapter() {
imageAdapter = new ImageAdapter(getApplicationContext(),
R.layout.seat_item, data);
gridview.setAdapter(imageAdapter);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(final AdapterView<?> arg0, final View view,
final int position, final long id) {
image= (ImageView) findViewById(R.id.seatItem);
if(showingFirst == true){
String message = "Clicked: " + position;
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
.show();
image.setImageResource(R.drawable.seat_blue);
showingFirst = false;
}else{
image.setImageResource(R.drawable.seat);
showingFirst = true;
}
}
}
ImageAdapter.java
public class ImageAdapter extends ArrayAdapter<Item> {
private Context mContext;
int resourceId;
ArrayList<Item> data = new ArrayList<Item>();
ImageView image;
// Constructor
public ImageAdapter(Context c,int layoutResourceId, ArrayList<Item> data) {
super(c, layoutResourceId, data);
this.mContext = c;
this.resourceId = layoutResourceId;
this.data = data;
}
#Override
public Item getItem(int position) {
System.out.println("Get: "+position);
return data.get(position);
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
final LayoutInflater layoutInflater =
(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.imgItem = (ImageView) convertView.findViewById(R.id.seatItem);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Item item = getItem(position);
System.out.println(position);
holder.imgItem.setImageDrawable(item.getImage());
return convertView;
}
static class ViewHolder
{
ImageView imgItem;
}
}
Use onItemClick second parameter view to access ImageView from ListView clicked row layout:
image= (ImageView)view.findViewById(R.id.seatItem);
At first glance I did not find anything wrong with your code. I would recommend you to try to delegate the click action to the clickable view itself instead of using an onItemClick, so in the getView method use a setonCLickListener to the image view, or the whole view if that is what suits your solution best.
In a side note I would also recommend that you do not use the activity as a callback since in most cases it will lead to an activity leak, create a class or use an anonimous class.
Hope this helps you.
Related
I am trying to implement a search function for android's grid view. However, every time i search a image , i do not get the correct image with its text. Below is my code. Any help is greatly appreciated :) My filter logic seems to be correct based on the log statements that i printed out. However the image and text is not filtered correctly.
MainActivity.
public class MainActivity extends AppCompatActivity {
final String TAG = "MainActivity";
GridView searchGrid;
ImageAdapter adapter;
int[] resourceIds = new int[]{R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5};
String[] names = new String[]{"sample 0", "sample 1", "sample 2", "sample 3", "sample 4",
"testImage"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchGrid = findViewById(R.id.searchGrid);
adapter = new ImageAdapter(this, this.getModels());
searchGrid.setAdapter(adapter);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
MenuItem item = menu.findItem(R.id.search_food);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
adapter.filter(s);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private List<DataModel> getModels() {
List<DataModel> models = new ArrayList<>();
DataModel dm;
for (int i = 0; i < names.length; i++) {
dm = new DataModel(resourceIds[i], names[i]);
models.add(dm);
}
return models;
}
class ImageAdapter extends BaseAdapter {
private Context mContext;
private List<DataModel> dataModels;
private List<DataModel> filterList = new ArrayList<>();
public ImageAdapter(Context context, List<DataModel> dataModels) {
mContext = context;
this.dataModels = dataModels;
this.filterList.addAll(dataModels);
}
#Override
public int getCount() {
return dataModels.size();
}
#Override
public Object getItem(int i) {
return dataModels.get(i);
}
#Override
public long getItemId(int i) {
return dataModels.indexOf(getItem(i));
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView;
if (view == null) {
// if it's not recycled, initialize some attributes
view = layoutInflater.inflate(R.layout.single_item, null);
imageView = view.findViewById(R.id.imageView);
TextView textView = view.findViewById(R.id.textView);
imageView.setImageResource(dataModels.get(i).resourceId);
textView.setText(dataModels.get(i).imageName);
}
return view;
}
public void filter(CharSequence text) {
String query = text.toString().toLowerCase();
//Log.i(TAG,query);
dataModels.clear();
if (text.length() == 0 ) {
dataModels.addAll(filterList);
} else {
for (DataModel dm : filterList) {
if (dm.imageName.toLowerCase().contains(query)) {
Log.i(TAG,dm.imageName + " " + query);
dataModels.add(dm);
}
}
}
notifyDataSetChanged();
}
}
MainActivity xml file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridView
android:padding="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchGrid"
android:numColumns="auto_fit"
android:columnWidth="120dp"
android:gravity="center">
</GridView>
</RelativeLayout>
single_item xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_below="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:layout_alignEnd="#+id/imageView"
/>
search_manu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/search_food"
android:title="Search Myfoods"
android:icon="#android:drawable/ic_menu_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
Try to change your code like this. Maybe it helps.
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView;
if (view == null) {
// if it's not recycled, initialize some attributes
view = layoutInflater.inflate(R.layout.single_item, null);
}
imageView = view.findViewById(R.id.imageView);
TextView textView = view.findViewById(R.id.textView);
imageView.setImageResource(dataModels.get(i).resourceId);
textView.setText(dataModels.get(i).imageName);
return view;
}
Your filter code is alright but you are not displaying the items properly. Even when your view is already initialized you need to fill correct data in the views else the view will show previous items data. Modify your code like this
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = layoutInflater.inflate(R.layout.single_item, null);
}
ImageView imageView = view.findViewById(R.id.imageView);
TextView textView = view.findViewById(R.id.textView);
imageView.setImageResource(dataModels.get(i).resourceId);
textView.setText(dataModels.get(i).imageName);
return view;
}
Also try using holder pattern so that you don't have to find view by its id everytime. It will save some run time on UI thread
When my spinner positioned at the actionbar is clicked, it's supposed to present a dropdown with an array of items. Every viewholder for an item has a name and a photo.
However, I want the spinner's title to be another layout (text-only).
In short: How can I set a layout for the title spinner that differs from the dropdown layout?
Main.java
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(this, dummyLists);
mMyListsSpinner.setAdapter(spinnerAdapter);
SpinnerAdapter.java
private class SpinnerAdapter extends BaseAdapter {
private String[] mListNames;
SpinnerAdapter(Context context, String[] listNames) {
this.mListNames = listNames;
}
#Override
public int getCount() {
if(this.mListNames == null) {
return 0;
}
return this.mListNames.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Context context = parent.getContext();
int spinnerItemViewLayout = R.layout.layout_spinner_dropdown_item;
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(spinnerItemViewLayout, parent, false);
TextView nameTextView = (TextView) view.findViewById(R.id.tv_spinner_list_name);
nameTextView.setText(this.mListNames[position]);
return view;
}
}
layout_spinner_dropdown_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearlayout_spinner_dropdown_item"
android:layout_width="222dp"
android:layout_height="#dimen/toolbar_actionbar_height"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_spinner_list_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="LIST"
android:textSize="#dimen/text_size_subheading"
android:textColor="#color/color_green_dark"/>
<ImageView
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:src="#color/color_green_dark"/>
</RelativeLayout>
This may be helpful: Android Spinner with different layouts for “drop down state” and “closed state”?
Basic points:
Rewrite getView() and getDropDownView() in your Adapter class [SpinnerAdapter]
In getView(), you should inflate normal layout for title bar, in your case it's a TextView only. In getDropDownView(), you should inflate your layout_spinner_dropdown_item.xml.
I have an app I am writing and it is already contains a lot of code, I decided I want to add a navigation drawer to the main activity toolbar but I don't know how to do it without creating a new navigation drawer project and copy my whole project to it which seems like a lot of work, is there a tutorial to add a navigation drawer to an existing project?
Create a layout layout_left_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bgLeftMenu">
<ImageView android:id="#+id/header"
android:src="#drawable/ic_launcher"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="26dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="30dp"
android:layout_marginStart="40dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="48dp"
android:layout_marginTop="26dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/header">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/pressed"/>
<TextView
android:id="#+id/userEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_below="#id/userName"
android:layout_centerInParent="true"
android:textColor="#color/pressed"
android:visibility="gone"/>
</LinearLayout>
</RelativeLayout>
<ListView android:id="#+id/menu_items_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/header"
android:dividerHeight="0dp"
android:divider="#null"
android:background="#color/bgLeftMenu"/>
<ProgressBar android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone"/>
</RelativeLayout>
Inflate it in a Custom View:
public class SimpleLeftMenuView extends NavigationView {
private LayoutInflater mInflater;
private Context mContext;
private ListView mItemsList;
private MenuItemsAdapter mItemsAdapter;
private ProgressBar mProgress;
private OnClickMenu mListener;
private ImageView mHeader;
private TextView userName;
private TextView userEmail;
//region Constructors
public SimpleLeftMenuView(Context context) {
super(context);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
public SimpleLeftMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
public SimpleLeftMenuView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initLayout();
setData();
}
//endregion
private void initLayout(){
mInflater.inflate(R.layout.layout_left_menu, this);
mItemsList = (ListView) findViewById(R.id.menu_items_list);
mProgress = (ProgressBar) findViewById(R.id.progress);
mHeader = (ImageView) findViewById(R.id.header);
userName = (TextView) findViewById(R.id.userName);
userEmail = (TextView) findViewById(R.id.userEmail);
mHeader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
}
public void setSelectedSection(String idSection) {
mItemsAdapter.setLastSelectedSection(idSection);
}
public void setmListener(OnClickMenu mListener) {
this.mListener = mListener;
}
private void setData() {
List<String> sections = new ArrayList<>();
sections.add(mContext.getString(R.string.home_id));
sections.add(mContext.getString(R.string.login_id));
sections.add(mContext.getString(R.string.settings_id));
//.........
//sections.add(mContext.getString(R.string.exit_id));
mItemsAdapter = new MenuItemsAdapter(mContext, sections, new OnClickMenu() {
#Override
public void onClick(String id) {
mItemsAdapter.setLastSelectedSection(id);
if (mListener != null)
mListener.onClick(id);
}
});
mItemsList.setAdapter(mItemsAdapter);
mItemsList.setSelection(0);
mItemsList.setItemChecked(0, true);
}
}
You have to create the MenuItemAdapter.
public class MenuItemsAdapter extends BaseAdapter {
private Context mContext;
private static String lastSelectedSection;
private List<String> mSections;
private int currentTextcolor;
private OnClickMenu mListener;
public MenuItemsAdapter(Context context, List<String> sections, OnClickMenu listener) {
mContext = context;
mSections = sections;
mListener = listener;
lastSelectedSection = sections.get(0);
}
#Override
public int getCount() {
return mSections.size();
}
#Override
public String getItem(int position) {
return mSections.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView, ViewGroup parent) {
final MenuItemHolder holder;
if (convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.layout_left_menu_item, parent, false);
holder = new MenuItemHolder(convertView);
convertView.setTag(holder);
}else {
holder = (MenuItemHolder) convertView.getTag();
}
Resources r = mContext.getResources();
int pxMarginSection = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, r.getDisplayMetrics());
holder.position = position;
holder.mLine.setVisibility(View.GONE);
holder.mTitle.setTextColor(mContext.getResources().getColor(R.color.primary));
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
if (mSections.get(position).equals(mContext.getString(R.string.login_id))) {
holder.mIconView.setImageResource(R.drawable.ic_login_gp);
// holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
holder.mTitle.setText(mContext.getString(R.string.action_login));
holder.mLine.setVisibility(View.VISIBLE);
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
} else if (mSections.get(position).equals(mContext.getString(R.string.settings_id))) {
holder.mIconView.setImageResource(R.drawable.option);
holder.mTitle.setText(mContext.getString(R.string.action_settings));
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
holder.mLine.setVisibility(View.VISIBLE);
} else if (mSections.get(position).equals(mContext.getString(R.string.exit_id))) {
holder.mIconView.setImageResource(R.drawable.shutdown);
holder.mTitle.setText(mContext.getString(R.string.salir));
holder.mLayoutItem.setPadding(0, pxMarginSection, 0, pxMarginSection);
holder.mLine.setVisibility(View.VISIBLE);
}
holder.mLayoutItem.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getActionMasked()){
case MotionEvent.ACTION_DOWN:
currentTextcolor = holder.mTitle.getCurrentTextColor();
holder.mLayoutItemSelect.setBackgroundColor(mContext.getResources().getColor(R.color.primary));
holder.mTitle.setTextColor(mContext.getResources().getColor(R.color.text_info));
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.text_info));
return true;
case MotionEvent.ACTION_UP:
holder.mLayoutItemSelect.setBackgroundResource(R.color.bgLeftMenu);
holder.mTitle.setTextColor(currentTextcolor);
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
mListener.onClick(mSections.get(position));
return true;
case MotionEvent.ACTION_CANCEL:
holder.mLayoutItemSelect.setBackgroundColor(mContext.getResources().getColor(R.color.bgLeftMenu));
holder.mTitle.setTextColor(currentTextcolor);
holder.mIconView.setColorFilter(mContext.getResources().getColor(R.color.primary));
return true;
}
return false;
}
});
return convertView;
}
class MenuItemHolder {
// butterKnife
View view;
#Bind(R.id.title)
TextView mTitle;
#Bind(R.id.icon)
ImageView mIconView;
#Bind(R.id.layoutItem)
LinearLayout mLayoutItem;
#Bind (R.id.rl_line)
View mLine;
#Bind(R.id.layoutItemSelect)
LinearLayout mLayoutItemSelect;
int position;
public MenuItemHolder(View itemView) {
ButterKnife.bind(this, itemView);
view = itemView;
}
}
public void setLastSelectedSection(String idSection) {
lastSelectedSection = idSection;
}
}
Now you have to modify your current Activity:
Change your main activity layout to use DrawerLayout and add your custom view "SimpleLeftMenuView":
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#EDEDED">
// YOUR CURRENT LAYOUT
<yourpackage.custom.SimpleLeftMenuView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/bgLeftMenu"/>
</android.support.v4.widget.DrawerLayout>
Activity class:
Add global variables:
protected #Bind(R.id.navigation_view) SimpleLeftMenuView mLeftMenuView;
protected #Bind(R.id.drawerLayout) DrawerLayout mDrawerLayout;
Set onclick listener. You can do an actions depends on the id:
mLeftMenuView.setmListener(new OnClickMenu() {
#Override
public void onClick(String id) {
Log.d("MENU", "ic_menu_hamburger clicked: " + id);
closeDrawer(null);
if (id.equals(getString(R.string.settings_id))) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
MainActivity.this.startActivity(intent);
} else if (id.equals(getString(R.string.exit_id))) {
// salir
showRateDialogBeforeExit();
}
}
});
I have created my own interface OnClickMenu:
public interface OnClickMenu {
void onClick(String id);
}
And add action to open drawer from menu icon:
#Override
public void onBackPressed() {
if((mDrawerLayout) != null && (mDrawerLayout.isDrawerOpen(GravityCompat.START)))
closeDrawer(null);
else {
super.onBackPressed();
}
}
public void closeDrawer(DrawerLayout.DrawerListener listener) {
mDrawerLayout.setDrawerListener(listener);
mDrawerLayout.closeDrawers();
}
public void openDrawer() {
mDrawerLayout.setDrawerListener(null);
mDrawerLayout.openDrawer(GravityCompat.START);
}
Menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
openDrawer();
return true;
}
return super.onOptionsItemSelected(item);
}
add to app build.gradle
compile 'com.android.support:design:26.0.0'
compile 'com.jakewharton:butterknife:8.6.0'
Change all #Bind to #BindView
The easiest way for you would be using this library.
Its really easy to implement and its very flexible.
If you want to do it yourself, consider reading official docs about creating navigation drawer.
I've tried the MaterialDrawer library, as suggested by #yury-dombaev and I have to admit it's far easier to implement than the official Navigation Drawer.
It's possible to implement either with Android X dependencies or with the normal ones.
In my case, since I have the normal ones, I've to stick with the MaterialDrawer 6.0.9v. Although there's a migration guide that I'll give a look.
To implement the library within your current activity do the following:
Add the dependencies in your app build.gradle as explained in Setup 1 of the v 6.0.9 of the library: https://github.com/mikepenz/MaterialDrawer/tree/v6.0.9
Add your drawer in the onCreate() method of your Activity: new DrawerBuilder().withActivity(this).build();.
Now you've got a basic (and useless) lateral menu. So it's time you continue reading the Material Drawer documentation and add menu elements :)
I am trying to make a listView that contains only images without texts but it gives a white screen and I am not getting any error or anything.
Here is my codes:
xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="3">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2">
<ListView
android:id="#+id/setOneListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" />
</RelativeLayout>
.........
</LinearLayout>
</LinearLayout>
Activity:
public class Set1_Activity extends Activity {
ListView list;
int[] images = {
R.drawable.iv1, R.drawable.iv2, R.drawable.iv3, R.drawable.iv4,
R.drawable.iv5, R.drawable.iv6, R.drawable.iv11, R.drawable.iv12,
R.drawable.iv13, R.drawable.iv14, R.drawable.iv15, R.drawable.iv16,
R.drawable.iv111, R.drawable.iv112, R.drawable.iv113, R.drawable.iv114,
R.drawable.iv115, R.drawable.iv116, R.drawable.iv7, R.drawable.iv8,
R.drawable.iv9, R.drawable.iv19, R.drawable.iv49, R.drawable.iv50,
R.drawable.iv52, R.drawable.iv54
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main2);
list = (ListView) findViewById(R.id.setOneListView);
HeartlessAdapter adapter = new HeartlessAdapter(this, images);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
switch(position){
case 0:
display.setImageResource(R.drawable.iv1);
tophone = R.drawable.iv1;
break;
.........
class HeartlessAdapter extends ArrayAdapter<String>
{
Context context;
int[] images;
HeartlessAdapter(Context c, int imgs[])
{
super(c, R.layout.imageview);
this.context=c;
this.images=imgs;
}
class MyViewHolder
{
ImageView myImage;
MyViewHolder(View v)
{
myImage = (ImageView) v.findViewById(R.id.imageView);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
MyViewHolder holder = null;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.imageview, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
}
else
{
holder = (MyViewHolder) row.getTag();
}
holder.myImage.setImageResource(images[position]);
return row;
}
}
All works fine, no error and the emulator just show empty white screen nothing inside. What could be missing?
Thanks!
Try moving the android:layout_weight="2" up a level to the horizontal LinearLayout.
1) Let HeartlessAdapter extend ArrayAdapter<Integer> instead of ArrayAdapter<String>.
2) on your constructor, call super(c, R.layout.imageview, imgs); It should work like that.
3) If you wanna optimize it a lot, remove the references to Context and the array of images from the adapter. You can get any item you need calling getItem(position) and the Context by calling getContext().
EDIT:
In order for it to work, call this:
super(c, R.layout.imageview, HeartlessAdapter.toIntegerArray(imgs));
and add this method to HeartlessAdapter:
private static Integer[] toIntegerArray(int[] array){
Integer[] finalArray = new Integer[array.length];
for (int i=0; i<array.length; i++){
finalArray[i] = array[i];
}
return finalArray;
}
try this...
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged()
}
});
I have managed to code to have images in each row of spinner but the images are all the same.I want to change each image. how do you do that. here is my xml and the code
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/calendar"/>
<TextView
android:id="#+id/weekofday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
here is java
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.row, R.id.weekofday, list);
dataAdapter.setDropDownViewResource(R.layout.row);
spinner.setAdapter(dataAdapter);
it displays the same image because it is set in the row.xml file. how do I make it dynamic?
Why don't you create Custom adapter and write the code accordingly. As far as I understand that , its showing same image because you have set it in row.xml. But how would adapter will know that the image should be changed on each row.
In Custom Adapter you can set the image as per the position (i.e. index) of Spinner Item
public class SavedSearchAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<SavedSearch> mData;
private boolean isEditMode = false;
public SavedSearchAdapter(Context context , ArrayList<SavedSearch> data){
mContext = context;
mData = data;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView tvTitle;
ImageView ivDelete;
if(convertView == null){
view = View.inflate(mContext, R.layout.screen_saved_search_item_row, null);
}
else{
view = convertView;
}
tvTitle = (TextView) view.findViewById(R.id.screen_saved_search_item_row_tv);
tvTitle.setText(mData.get(position).name);
ivDelete = (ImageView) view.findViewById(R.id.screen_saved_search_item_row_iv_delete);
view.setTag(mData.get(position));
return view;
}
}