How to show listview in a sliding menu? - android

I have a main activity and sliding menu beneath it I want to add a list items to the sliding menu I think my code is right but the list still not showing in the sliding section:
package com.example.example;
import java.util.ArrayList;
import java.util.Arrays;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity;
public class ExampleActivity extends Activity {
private ListView mainMenu ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the content view
setContentView(R.layout.activity_example);
View v = getLayoutInflater().inflate(R.layout.sliding_menu, null,true);
// setBehindContentView(v);
// Find the ListView resource.
mainMenu = (ListView) v.findViewById( R.id.exampleMenu );
// Create and populate a List of menu items names.
String[] menuText = new String[] { "Top 20", "League"};
ArrayList<String> menuList = new ArrayList<String>();
menuList.addAll( Arrays.asList(menuText) );
// Create ArrayAdapter using the menu list.
listAdapter = new ArrayAdapter<String>(this, R.layout.menu_item, menuList);
// Set the ArrayAdapter as the ListView's adapter.
mainMenu.setAdapter( listAdapter );
// configure the SlidingMenu
SlidingMenu menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.sliding_menu);
}
}
I am new to android I just want to know do I miss something here ? because the app is working but the menu is not showing . Should I add something to the code?
Edit: the setMenu as it described in the SlidingMenu.java of the sliding menu lib :
/**
* Set the behind view (menu) content from a layout resource. The resource will be inflated, adding all top-level views
* to the behind view.
*
* #param res the new content
*/
public void setMenu(int res) {
setMenu(LayoutInflater.from(getContext()).inflate(res, null));
}
/**
* Set the behind view (menu) content to the given View.
*
* #param view The desired content to display.
*/
public void setMenu(View v) {
mViewBehind.setContent(v);
}
/**

I am not familiar with Sliding menu library , but what I can see from the code is that these two lines are reason for your issue
setBehindContentView(R.layout.sliding_menu);
View v = getLayoutInflater().inflate(R.layout.sliding_menu, null);
they create two different views one goes to the actulay layout rendering and one you are creating and taking listview to set data but never added to the activity content.
I hope if you change those two lines some thing like this might work
View v = getLayoutInflater().inflate(R.layout.sliding_menu, null);
//set this v to setMenu instead of R.layout.sliding_menu
//your codes......
//
//
//menu.setMenu(R.layout.sliding_menu);
menu.setMenu(v);

Related

How to disable a single row and change its background color in a listview, without a button (or a method if possible)?

The title of this post says it all.
This code works without any problems:
package abc.AvailableCars;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class carListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon", :Sentra GXE"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
dButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(3).setEnabled(false);
carListview.getChildAt(3).setBackgroundColor(Color.parseColor("#3f51b5"));
}
});
}
}
This is in my listview .xml file:
<Button
android:id="#+id/disable_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable A Row"
/>
But, when I comment-out everything that belongs to the button, like below, and the Car List class is called, the app crashes with the error in the Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference:
final ListView carListview = (ListView) findViewById(R.id.list_view);
//final Button dButton = (Button) findViewById(R.id.disable_button);
String[] cars = {"Maxima GXE", "Passat", "Focus SE", "Mazda6", "Avalon"};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
carListview.setAdapter(arrayAdapter);
//dButton.setOnClickListener(new View.OnClickListener() {
//#Override
//public void onClick(View v) {
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
//});
}
//}
I'm not an Android newbie anymore, but this is eluding me.
I want the chosen row to be disabled and the color set as soon as the listview is shown.
How can I do this programmatically without a button?
I have tried every variation I can think of, getView(), even a fake click.
Just in case it makes a difference, this code is in a separate class and file than the MainActivity.java file, and is called in that file.
There has to be a simple answer. What do I need to change?
Please be verbose.
Thank you.
You are calling carListview.getChildAt(chosenRow) when you set up your list view, in onCreate. Your list view is not ready yet. Try moving this code to your onResume - should look something like this:
#Override
public void onResume(){
super.onResume();
arrayAdapter.notifyDataSetChanged();
int chosenRow = 3;
carListview.getChildAt(chosenRow).setEnabled(false);
carListview.getChildAt(chosenRow).setBackgroundColor(Color.parseColor("#3f51b5"));
}
This is a pretty simple case - your chosenRow number is generated by you. You might need a custom Adapter if you need it to be algorithmic or user-driven. Have a look at this tutorial.
From my understanding, since listViews are views, they have to be Overridden for some things to be changed in them.
I chose not to disable the required rows, but check for them in code.
The complete code that works is below.
Some credit goes to Raghunandan for his/her answer at-
Android - Change background color of specific item of ListView
Again, sorry, but the indentation of the code wouldn't work correctly for some reason.
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CarListActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.car_list_layout);
final ListView carListview = (ListView) findViewById(R.id.list_view);
String[] cars = {"European Cars:", "Mercedes", "Passat", "Bently", "Porsche", "BMW", "Yugo","Land Rover",
"Japanese Cars:", "Maxima GXE", "Mazda6", "Avalon", "Toyota", "Honda", ""};
final List<String> list_of_cars = new ArrayList<String>(Arrays.asList(cars));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_of_cars);
//------------------------------------------
carListview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list_of_cars) {
// Since listViews are views, they have to be Overrdden for some things to be changed in them.
#Override
public View getView(int rowPosition, View convertView, ViewGroup parent) {
View row = super.getView(rowPosition, convertView, parent);
//------------------------------------------
// This works. I have only tried this for two rows, the two I wanted. I expected this line to crash the app, but it didn't.
if(getItem(rowPosition).equals("European Cars:") || getItem(rowPosition).equals("Japanese Cars:")) {
// Make the two rows have a white background color.
row.setBackgroundColor(Color.WHITE); // this command WORKS fine by itself.
// row.setEnabled(false); this command caused "bleeding" over into other rows, so I will check for the rows in a condition.
} // both of the getItems end here.
else {
// All of the other rows should have this color.
row.setBackgroundColor(Color.parseColor("#EEE8AA"));
// the default color
} // else ends here.
//------------------------------------------
return row;
//------------------------------------------
} // getView ends here.
}); // carListview.setAdapter ends here.
} // onCreate ends here.
} // CarListActivity ends here.
Thanks, and I hope this helps others.

Android Multi-Line Listview in fragment

I have an app that uses a tab layout using fragments, in one of the fragments I would like to have a two/multi-line List View, I have been following this tutorial which shows it for a ListActivity. I have copied the code into my fragment and cannot seem to get it to work. all of my code for the layout of the fragment and the two lines is the same as code in the link above, with the exception of the Java class for the fragment I want to show the list in.
The code for the fragment is as follows:
package com.example.shopsellswap;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
public class Fragment_My_Profile extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myProfileView = inflater.inflate(R.layout.fragment_my_profile, container, false);
return myProfileView;
}
//ArrayList holds the data (as HashMaps) to load into the ListView
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
//SimpleAdapter does the work to load the data in to the ListView
private SimpleAdapter sa;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//HashMap links each line of data to the correct TextView
HashMap<String,String> item;
for(int i=0;i<StatesAndCapitals.length;i++){
item = new HashMap<String,String>();
item.put( "line1", StatesAndCapitals[i][0]);
item.put( "line2", StatesAndCapitals[i][3]);
list.add( item );
}
sa = new SimpleAdapter(Fragment_My_Profile.this, list,
R.layout.my_two_lines,
new String[] { "line1","line2" },
new int[] {R.id.line_a, R.id.line_b});
setListAdapter(sa);
}
private String[][] StatesAndCapitals =
{{"Alabama","Montgomery"},
{"Alaska","Juneau"},
{"Arizona","Phoenix"},
{"Arkansas","Little Rock"},
{"California","Sacramento"}};
The part that is giving me errors is
sa = new SimpleAdapter(Fragment_My_Profile.this, list,
R.layout.my_two_lines,
new String[] { "line1","line2" },
new int[] {R.id.line_a, R.id.line_b});
setListAdapter(sa);
the specific error is:
The constructor SimpleAdapter(Fragment_My_Profile, ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined
what's weird is when I change ListFragment to ListActivity the error is no longer there
Why it isn't working and how I can fix it?
ListFragment is not a subclass of Context, while ListActivity is. You must pass some type of Context to this constructor. For example, let's assume that your Activity (or FragmentActivity) class is named MainActivity:
sa = new SimpleAdapter(MainActivity.this, list, ...
Depending on when you create this Fragment that might not work, so you can move all of your code in onCreate() to the onActivityCreated() method and use:
sa = new SimpleAdapter(getActivity(), list, ...

Android - Show textview by clicking on listview item

I am creating my very first Android application, but i stuck unfortunately. The application would be very simple: On the starting page there is a ListView with items like:
1st group
2nd group
3rd group
...
By clicking on any of these items a new page would show up with a single textview element that would have some description. Like you click on '1st group' item, the listview gets hidden, and a new page appears with '1st group description' text.
So far I can show the listview with the items, but when I click on them, nothing happens (i guess I miss some basic stuff, but as a very newby, i cannot find it out easily).
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.view.*;
public class SimpleListViewActivity extends Activity {
LinearLayout.LayoutParams layoutParams;
LinearLayout ll;
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// populate the List of groups
String[] GROUP = getResources().getStringArray(R.array.group);
ArrayList<String> GrList = new ArrayList<String>();
GrList.addAll( Arrays.asList(GROUP) );
// Create ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, GrList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
ll = (LinearLayout)findViewById(R.id.LinearLayout);
layoutParams = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView t = (TextView) findViewById(R.id.textView1);
String[] DESC = getResources().getStringArray(R.array.desc);
t.setText(DESC[position]);
ll.addView(t);
//This is the point that is wrong for sure (and others maybe also). I cannot get the textview shown
}
});
}
}
Thanks for your help.
Have you tried displaying a toast message or setting a breakpoint within your onItemClick() method to verify that its not being reached? My guess is that it is and you are running into one of the issues described here:
Refreshing a LinearLayout after adding a view
I am assuming your R.layout.main is holding a listview and a linear layout with ids R.id.mainListView, and R.id.LinearLayout respectively.
Example: I left out some of the obvious attributes you would need like height width etc..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
>
<ListView android:id="#+id/mainListView" />
<LinearLayout android:id="#+id/LinearLayout" />
</RelativeLayout>
In your on item click, all you will do is add a textview as you have done, then set the mainListView.setVisibility(View.INVISIBLE) and ll.setVisibility(View.VISIBLE).
If your R.layout.main is not using a RelativeLayout as the root node, but is instead using a LinearLayout you should still be able to achieve the same effect by setting the Visibilities to View.GONE if you want it to hide, and View.VISIBLE if you want it to show.
To revert back to being able to see the list view I would override onBackPressed() in the activity, to invert the Visibilities on the two items. Also remember to remove all views from the linear layout so that the next time an item in the group is selected it will be the only item in the linear layout when it is added.
There are much easier ways to accomplish this, such as firing off a new activity for viewing the next item, but seems you are keeping everything within one activity. I would also think about using a ListActivity instead of base activity class.
Hope this helps.
First off stop using the word page. Call it an activity (gotta get you in the Android zone)
Once the click happens start a new activity like so:
mainListView.setOnItemClickListener(new OnItemClickListener() {
String textToPass = GrList.get(position)
Intent i = new Intent(getBaseContext(), SecondActivity.class);
i.putExtra("textToPass", textToPass);
startActivity(i);
}
You'll obviously need to have that second activity with its corresponding layout file defined. Also in the second activity look up how to get the bundle and extras from the first activity in order to get the textToPass String

spinner cannot be resolved or is not a field

I am studying ApiDemos sample in SDK
and trying to separate Menu example(App/Menu/Inflate from Menu-MenuInflateFromXml.java).
package my.android.Menu;
import my.android.Menu.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MyMenu extends Activity {
/**
* Different example menu resources.
*/
private static final int sMenuExampleResources[] = {
R.menu.title_only, R.menu.title_icon, R.menu.submenu, R.menu.groups,
R.menu.checkable, R.menu.shortcuts, R.menu.order, R.menu.category_order,
R.menu.visible, R.menu.disabled
};
/**
* Names corresponding to the different example menu resources.
*/
private static final String sMenuExampleNames[] = {
"Title only", "Title and Icon", "Submenu", "Groups",
"Checkable", "Shortcuts", "Order", "Category and Order",
"Visible", "Disabled"
};
/**
* Lets the user choose a menu resource.
*/
private Spinner mSpinner;
/**
* Shown as instructions.
*/
private TextView mInstructionsText;
/**
* Safe to hold on to this.
*/
private Menu mMenu;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a simple layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Create the spinner to allow the user to choose a menu XML
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sMenuExampleNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner = new Spinner(this);
// When programmatically creating views, make sure to set an ID
// so it will automatically save its instance state
mSpinner.setId(R.id.spinner);//Error Line
mSpinner.setAdapter(adapter);
setContentView(R.layout.main);
}
}
IDE show this error "spinner cannot be resolved or is not a field", i can't go head.
i did't see any XML file which include "spinner".
As per Tim's comment above:
put this line in your onCreate()
mSpinner = (Spinner) findViewById(R.id.spinner);
You should move your setContentView(R.layout.main); right below of the super.onCreate(savedInstanceState); It's necessary to set the content of your activity before using its Views and you don't need to instanciate the spinner View programmatically. Simply use the Spinner defined at the main.xml file (I Assume you have a Spinner inside this file).
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a simple layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Create the spinner to allow the user to choose a menu XML
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, sMenuExampleNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//mSpinner = new Spinner(this);
// When programmatically creating views, make sure to set an ID
// so it will automatically save its instance state
// mSpinner.setId(R.id.spinner);//Error Line
mSpinner = (Spinner) findViewById(R.id.you_spinner_id); //you_spinner_id must be defined at main.xml
mSpinner.setAdapter(adapter);
}

How to show previous list view using back button

Suppose I have displayed a list view(say lv1) of 3 items. when clicked on any of them I get new list view(say lv2). when again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. lv2 and again when back button is pressed I want to show list view lv1. can anybody tell me how I can do this?
If you want to shown different listviews in different activities. Follow Shailendra Rajawat's guide. Every time you click on an item, start a new Activity. So by default, when you press back button, the previous activity will be shown.
If you want to achieve this function within one activity. Use a variable to indicate which listview should be currently shown. Something like:
private int listIndex=0; every time you click on an item:listIndex++; and call setContentView(lvX); to show new listView.
Override the onBackPress() method:
if(listIndex>0) *so at the first listView backbutton will be ignored */
listIndex--;
switch(listIndex) {
case 0:
setContentView(lv0); break;
/* some other cases*/
........}
Something like this.
EDIT: I tested my method. Actually, there are three ways to refresh the listView.
package viewTest.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
public class ViewTestActivity extends Activity {
private ArrayAdapter<String> adapter0;
private ArrayAdapter<String> adapter1;
private String[] array0;
private String[] array1;
private ListView lv0;
private ListView lv1;
private RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array0 = getResources().getStringArray(R.array.LV0);
array1 = getResources().getStringArray(R.array.LV1);
adapter0 = new ArrayAdapter<String>(this, R.layout.item, array0);
adapter1 = new ArrayAdapter<String>(this, R.layout.item, array1);
lv0 = new ListView(this);
lv1 = new ListView(this);
layout=(RelativeLayout)findViewById(R.id.layout);
lv0.setAdapter(adapter0);
lv1.setAdapter(adapter1);
lv0.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//Method1: change the adapter to refresh the listview
// lv0.setAdapter(adapter1);
//Method2: use the layout to remove and add views
// layout.removeAllViews();
// layout.addView(lv1);
//Method3: setContentView() directly;
setContentView(lv1);
}
});
// layout.addView(lv0);
setContentView(lv0);
}
}
what you have described here it is obvious in Android Activity life cycle because when you hit back button it finish the current Activity and show the top most Activity on Stack . So please explain what problem you are getting here .
You can put some boolean to true if the second list view is showing. When back button is pressed, look at the boolean and change the listView to the first one.
as a neat and clean approach every screen you want to show on back press , should be on activity stack , so for every such views start a new activity even if they have same UI components .
if this approach is not suitable save data of every visible entity on navigations they reset views as per need by overRiding onBackPress().

Categories

Resources