Implementing Action Bar in list view - android

I want to implement an ActionBar in a listview.
As given in developer.android.com I tried using extends ActionBar activity in my code.
My code runs fine when I give extends Activity, But I won't get an ActionBar.
The code crashes when I use extends ActionBarActivity with java.lang.exceptionininitializererror.
I have imported support library. The screenshot is attached.
The imported libraries are android-support-v4.jar
android-support-v7-appcompat.jar.
Below is my code.
Please guide me on this.
Also please let me know if I can do it using any other way.
public class ImageTextListViewActivity extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Football",
"Basketball" };
public static final Integer[] images = { R.drawable.football,
R.drawable.basketball };
ListView listView;
List<RowItem> rowItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayShowTitleEnabled(false);
//android.graphics.drawable.ColorDrawable.setColor(0xff9ACC00);
//actionBar.setBackgroundDrawable(colorDrawable);
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Navigation to next page
Intent myIntent = new Intent(view.getContext(), Football.class);
myIntent.putExtra("Game",listView.getItemAtPosition(position).toString());
startActivityForResult(myIntent, 0);
//Navigation ends
}
}

You have to add appcompat library as a library project not just import the jar.
Import appcompat into your IDE from android_sdk_dir/extras/android/support/v7/appcompat.
Add it to your project as a library project. (Project -> Properties -> Android -> Library -> Add.. and select appcompat).
Don't forget to change the application theme to Theme.AppCompat.

Related

Android List View Navigation

I am a beginner and trying to do my first android app.
I have the following requirement.
When the user clicks on the item in the list, we should be able to navigate to a new page based on the item clicked.
Right now I have a sample code wherin I am able to navigate to only one page irrespective of the item clicked.
For exmple, When I click on football in list I should be able to navigate to a new page called by football class and when I click on basketball I should be able to navigate to a new page called by basketball class.
Also I want to add an actionbar to this listview.
I am able to create an actionbar with home, logout and settings option separately . But I am not able to add it to this list view.
Please suggest regarding how to go about this
Below is my code:
public class ImageTextListViewActivity extends Activity implements
OnItemClickListener {
public static final String[] titles = new String[] { "Football",
"Basketball" };
public static final Integer[] images = { R.drawable.football,
R.drawable.basketball };
ListView listView;
List<RowItem> rowItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Navigation to next page
Intent myIntent = new Intent(view.getContext(), Football.class);
myIntent.putExtra("Game",listView.getItemAtPosition(position).toString());
startActivityForResult(myIntent, 0);
//Navigation ends
}
}
Why don't you use the position param of onItemClick method?

How to add a Listview with SubItems

I would like to display the data in an array of string as the Subitems of the listview.
How exactly could I do it?
Is this what you are trying to achieve?
This is part of my code from an ap that uses fragments. One fragment is a list fragment.
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Category List extends ListFragment {
final static String[] CATEGORIES = {"String1","String2",
"String3","String4"};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1,
CATEGORIES));
Hope it helps.
Download the api demos from the Android Development site or open the SDK Manager and ensure you have downloaded Samples for your current SDK.
Then navigate to the samples folder and take a look at expandable lists. There are a few fully working examples there.
On my WinXP comp the files are located here:
C:\Program Files\Android\android-sdk\samples\android-16\ApiDemos\src\com\example\android\apis\view then look for the expandable lists.jar files
You need to create an Adapter class. Here is your solution:
First create a private class in your MainActivity class like this:
private class Adapter extends BaseAdapter
{
ArrayList<String> list;
public Adapter(ArrayList<String> list)
{
this.list=list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public String getItem(int index)
{
return list.get(index);
}
#Override
public long getItemId(int arg0)
{
return 0;
}
#Override
public View getView(int index, View view, ViewGroup arg2)
{
TextView tv_text = new TextView(MainActivity.this);
tv_text.setText(list.get(index));
tv_text.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
#SuppressWarnings("deprecation")
AbsListView.LayoutParams params =
new AbsListView.LayoutParams(AbsListView.LayoutParams.FILL_PARENT,
AbsListView.LayoutParams.FILL_PARENT);
tv_text.setLayoutParams(params);
tv_text.setHeight(60);
tv_text.setTextSize(18);
return tv_text;
}
}
then you need to put the Strings in ArrayList<String> :
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<yourArray.length(); i++) list.add(yourArray[i]);
after that you need to create an instance of the Adapter class:
Adapter adapter = new Adapter(list);
then you need to set the adapter as the main adapter of your ListView :
ListView lv_list = (ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
D

setOnItemClickListener not working

I am not able get onItemCickListener to work. All I am doing is opening up a fragment using intents. Please do let me know if I am doing anything fishy here ?
public class MyListFragment extends ListFragment {
private ArrayList<String> myList = null;
private ArrayAdapter<String> myAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
Log.d("Example:", "In Fragement Calss");
super.onActivityCreated(savedInstanceState);
Resources myResources = getResources();
myList = new ArrayList<String>(Arrays.asList(myResources.getStringArray(R.array.myExamArray)));
myAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,myList);
setListAdapter(myAdapter);
ListView lv = (ListView) getActivity().findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(), DetailsFragment.class);
startActivity(myIntent);
}
});
}
}
Note that the ListView blocks clicks of an item that contains at least one focusable
descendant but it doesn’t make the content focus-reachable calling
setItemsCanFocus(true). One workaround is by disabling focusability of descendants, using
android:descendantFocusability="blocksDescendants"
in the layout defining your list item. (First learned of this myself from http://cyrilmottier.com/2011/11/23/listview-tips-tricks-4-add-several-clickable-areas/, but a few other SO posts also point this out.) Does your layout contain buttons? If so, you'd fall into this case.
I don't see where you are inflating a specific XML for this Fragment... but it is possible you are referencing the wrong ListView.
Regardless you should use the existing onListItemClick method:
public class MyListFragment extends ListFragment {
private ArrayList<String> myList = null;
private ArrayAdapter<String> myAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
// Remove the OnItemClickListener, but keep everything else
}
#Override
public void onListItemClick (ListView l, View v, int position, long id) {
Intent myIntent = new Intent(this, DetailsFragment.class);
startActivity(myIntent);
}
}

ListView update

I have two activities with ListView. This two activitises have individual layout-file. First have myListView01, second have myListView02. How to update listView's adapters?
I do so:
ListView list = (ListView)findViewById(R.id.myListView01);
myAdapter = new ArrayAdapter<String>(this, R.layout.item01, R.id.label, array01);
list.setAdapter(myAdapter);
I remove some items from the array01 and I need to update my listView without this elements.
But this solution to ListActivity does not work:
myAdapter.notifyDataSetChanged();
my code:
package ...;
import ...;
public class Class01 extends Activity
{
ArrayAdapter<String> mAdapter;
ArrayList<String> array01 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout01);
ListView list = (ListView)findViewById(R.id.my_list01);
mAdapter = new ArrayAdapter<String>(this, R.layout.item01, R.id.label, array01);
list.setAdapter(mAdapter);
}
public void onListItemClick (ListView parent, View v, int position, long id)
{
array01 = deleteElementByPosition(array01, position);
mAdapter.notifyDataSetChanged(); //does not work
}
public void deleteElementByPosition()
{
...
}
}
You have not set onItemClickListener for your ListView.
Extend your Class01 from ListActivity. Activity class doesn't have onListItemClick() method so it is never invoked. Or set your listener with setOnItemClickListener() for your ListView.

Adding spinner via java code rather than XML in Tabwidget

I'm new to android. Recently I learn how to create Tabwidget. This function is useful. But I find that I cannot add the widgets I want in R.layout.xxxx. So I try to do it by java code. But unfortunately it failed.
By using XML, I do the following. The program works without problem.
public class ShowBalanceActivity extends Activity implements AdapterView.OnItemSelectedListener
{
private Spinner monthview;
private ArrayAdapter monthadapter;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.balance);
monthadapter = ArrayAdapter.createFromResource(
this, R.array.months, android.R.layout.simple_spinner_item);
monthadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
monthview = (Spinner) findViewById(R.id.monthlist);
monthview.setOnItemSelectedListener(this);
monthview.setAdapter(monthadapter);
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
}
For the Java code part, I use the following,
public class BalanceLayout extends TabActivity implements TabHost.TabContentFactory
{
private Activity activity;
private LayoutInflater inflaterHelper = null;
private Spinner monthview = null;
private LinearLayout layout;
private static final String Tab1 = "By Date";
private static final String Tab2 = "By Categories";
private ArrayAdapter <String> monthadapter = null;
public BalanceLayout (Activity a)
{
activity = a;
inflaterHelper = a.getLayoutInflater();
}
public View addCustomView(String id)
{
layout = new LinearLayout(activity);
layout.setOrientation(LinearLayout.VERTICAL);
if(id.equals(Tab1))
{
Spinner monthview = new Spinner(activity);
ArrayAdapter <String> monthadapter = new ArrayAdapter <String> (this,
android.R.layout.simple_dropdown_item_1line, MONTHS);
monthadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
monthview.setAdapter(monthadapter);
monthview.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
layout.addView(monthview,
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
else if(id.equals(Tab2))
{
}
return layout;
}
}
But it causes force close when I execute the program. It seems that I cannot use findViewById method to create the view like XML.
I read many documentations and search android docs and internet. I cannot find the solution. Hope that some of you know what happened to my code and solution to solve
Thanks !!
Tom
After I checked my code and debug. Finally it is easy to solve. But originally I don't know why. Then I isolate the problem by only inserting textview.
TextView tv = new TextView(activity);
tv.setText("This is a text view");
layout.addView(tv, new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
The problem for my code is using "this" not "activity". It is because I want to create layout dynamically not using content factory or intent method. So "this" was replaced by activity. Then the problem is solved. But I spent much time to troubleshoot. Android is amazing
monthadapter = ArrayAdapter.createFromResource(
activity, R.array.months, android.R.layout.simple_spinner_item);
monthadapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

Categories

Resources