GridView items are not selectable in Fragment - android

I have a Fragment in an Activity and I'm trying to display a GridView` from a custom adapter.I'm able to display the GridView but unable to select any item of the gridview.
Can any one help me in identifying the issue.
Please find the code I have used :
//MainActivity
package com.example.frag;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.os.Build;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
GridView optionsGridView;
ArrayList<InfoItems> items = new ArrayList<InfoItems>();
OptionsAdapter adapter;
String items2[] = {"1","2","3","4"};
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
// implentation of display of options in GridView
optionsGridView = (GridView) rootView.findViewById(R.id.optionsGrid);
/*items.add(new InfoItems("Passport"));
items.add(new InfoItems("Aadhar"));
items.add(new InfoItems("Pan"));
items.add(new InfoItems("DL"));*/
adapter = new OptionsAdapter(this.getActivity(), items2);
optionsGridView.setAdapter(adapter);
return rootView;
}
}
}
Custom Adapter
package com.example.frag;
import java.util.ArrayList;
import dalvik.bytecode.OpcodeInfo;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class OptionsAdapter extends BaseAdapter{
private Context context;
private ArrayList<InfoItems> infoItems;
String items[];
public OptionsAdapter(Context context,ArrayList<InfoItems> items) {
// TODO Auto-generated constructor stub
this.context = context;
this.infoItems = items;
}
public OptionsAdapter(Context contsxt,String txt[]) {
// TODO Auto-generated constructor stub
this.context = contsxt;
this.items = txt;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return infoItems.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.info_options, null);
}
TextView option = (TextView) convertView.findViewById(R.id.optionsItem);
option.setText(items[position]);
return convertView;
}
}
fragment xml -- layout which will be displayed in the fragment
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.frag.MainActivity$PlaceholderFragment" >
<GridView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/optionsGrid"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:numColumns="2"
android:gravity="center"
android:layout_marginTop="10dp"/>
</RelativeLayout>
item xml -- list item of the custom adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000"
android:clickable="true">
<TextView android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="10dp"
android:gravity="center"
android:textColor="#f000ff"
android:textSize="20sp"
android:textStyle="bold"
android:id="#+id/optionsItem"
android:text="passport"
android:clickable="true"
android:layout_gravity="center"/>
</LinearLayout>

Squonk is correct, you need to call optionsGridView.setAdapter(new OnItemClickListener....). You could also implement OnItemClickListener in your fragment and call optionsGridView.setAdapter(this).

Inside your PlaceholderFragment put this like below :
optionsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//do your stuff!
}
});

Related

How to select item in the list view programmatically

I have an ArrayList<String> List which contains some items from the listview all_list. How can I select these items in the list view all_list programmatically by checking the ArrayList<String> List contents?
for e.g., listview all_list contains [0] apple
[1] orange
[2] banana
In ArrayList<String> List, I have orange so I want item on position 1 on the listview all_list to be selected (highlighted) automatically.
I have tried using all_list.setItemChecked(), but it does nothing and shuts down the application. I am performing the operation after listing the adapter.
set an onItemClickListener to the listview such that on click, you set a boolean flag that sets the checkbox in each row to selected. then call notifyDataSetChanged()
Try this
MainActivity.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView1;
ArrayList<ModelClass> modelClass = new ArrayList<ModelClass>();
FruitSelectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelClass.add(new ModelClass("Orange", true));
modelClass.add(new ModelClass("Apple", false));
modelClass.add(new ModelClass("Banana", false));
modelClass.add(new ModelClass("Grapes", false));
listView1 = (ListView) findViewById(R.id.listView1);
adapter = new FruitSelectAdapter(MainActivity.this, modelClass);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(modelClass.get(arg2).isSelected()){
modelClass.get(arg2).setSelected(false);
}else{
modelClass.get(arg2).setSelected(true);
}
adapter.notifyDataSetChanged();
}
});
}
}
activity_main.xml
<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="com.example.multiseekbar.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
</ListView>
</RelativeLayout>
FruitSelectAdapter.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FruitSelectAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<ModelClass> modelClass=null;
public FruitSelectAdapter(Activity activity, ArrayList<ModelClass> modelClass) {
this.activity = activity;
this.modelClass = modelClass;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return modelClass.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return modelClass.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder =new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.txtFruitName = (TextView)convertView.findViewById(R.id.txtFruitName);
holder.cbFruitSelectStatus = (CheckBox)convertView.findViewById(R.id.cbFruitSelectStatus);
holder.linLayBackground = (LinearLayout) convertView.findViewById(R.id.linLayBackground);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtFruitName.setText(modelClass.get(position).getFruitName());
holder.cbFruitSelectStatus.setChecked(modelClass.get(position).isSelected());
if(modelClass.get(position).isSelected()){
holder.linLayBackground.setBackgroundColor(Color.parseColor("#80ccff"));
}else{
holder.linLayBackground.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
class ViewHolder{
TextView txtFruitName;
CheckBox cbFruitSelectStatus;
LinearLayout linLayBackground;
}
}
row1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/linLayBackground"
android:layout_height="70dp"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtFruitName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Fruit name"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#000000" />
<CheckBox
android:id="#+id/cbFruitSelectStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
ModelClass.java
package com.example.multiseekbar;
public class ModelClass {
String fruitName;
boolean isSelected=false;
public ModelClass(String fruitName, boolean isSelected) {
this.fruitName = fruitName;
this.isSelected = isSelected;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}

Why this custom adapter does not show output

I'm new in android. I have tried a custom adapter but output is not visible. apparently there is no error.Kindly mention where I'm doing wrong.
Here is code
package com.example.customadapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.TextView;
public class MainActivity extends Activity {
GridView gridview;
static final String[] Box_Clrs=new String[]{
"pink" , "red" , "blue"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview= (GridView) findViewById(R.id.grid_view);
gridview.setAdapter(new ImageAdapter(this, Box_Clrs));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
Toast.makeText(
getApplicationContext(),((TextView) v.findViewById(R.id.grid_text))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#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);
}
}
ImageAdapter.java
package com.example.customadapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
Context context;
final String[] clrValues;
public ImageAdapter(Context context, String[] clrValues)
{
this.context=context;
this.clrValues=clrValues;
}
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if(convertView==null)
{
gridView = new View(context);
gridView = inflater.inflate(R.layout.mobile,null);
TextView textview=(TextView) gridView.findViewById(R.id.grid_text);
textview.setText(clrValues[position]);
ImageView imageview=(ImageView) gridView.findViewById(R.id.image);
String clr= clrValues[position];
if(clr.equals("pink"))
imageview.setImageResource(R.drawable.pink);
else if(clr.equals("red"))
imageview.setImageResource(R.drawable.red);
else
imageview.setImageResource(R.drawable.blue);
}
else
{
gridView=(View) convertView;
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return clrValues.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position){
// TODO Auto-generated method stub
return 0;
}
}
activity_main.xml
<GridView 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"
android:id="#+id/grid_view"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:numColumns="auto_fit"
tools:context="com.example.customadapter.MainActivity" >
mobile.xml
<LinearLayout 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"
android:padding="5dp"
tools:context="com.example.customadapter.MainActivity" >
<ImageView
android:id="#+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#drawable/blue">
</ImageView>
<TextView
android:id="#+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
</TextView>
You are missing convertView = gridView; after inflating and populating your list item layout. I find it easier to do something like this:
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, parent, false);
}
// do your setup here
return convertView;
getView method should return item of your grid view instead of gridview itself
try to use something like this:
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
View view
if(convertView==null)
{
view = inflater.inflate(R.layout.mobile,parent, false);
} else {
view = convertView;
}
TextView textview=(TextView) view.findViewById(R.id.grid_text);
textview.setText(clrValues[position]);
ImageView imageview=(ImageView) view.findViewById(R.id.image);
String clr= clrValues[position];
if(clr.equals("pink"))
imageview.setImageResource(R.drawable.pink);
else if(clr.equals("red"))
imageview.setImageResource(R.drawable.red);
else
imageview.setImageResource(R.drawable.blue);
return view;
}
You should also improve methods:
#Override
public Object getItem(int position) {
return clrValues[position];
}
#Override
public long getItemId(int position){
return position;
}
See a tutorial on custom adapters http://www.vogella.com/tutorials/AndroidListView/article.html#adapterown
Try this;
Change below;
View gridView;
if(convertView==null)
{
gridView = new View(context);
gridView = inflater.inflate(R.layout.mobile,null);
…………
}
To;
View gridView = convertView;
if(gridView==null)
{
gridView = inflater.inflate(R.layout.mobile,null);
………………
}

How to implement onClickListener on a custom adapter?

I am learning to make a simple time table managing application.
I have a list of courses displayed. Each item in a list is a textview + a delete button. The onClick Listener in my list item isn't working as expected. When I click on the delete button, it is working fine. However, I want to open up some other activity when user clicks on the textview of the list item.
Code:
ShowAll.java (the main activity in which I am displaying a list of classes)
package com.example.android.mytimetable;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class ShowAll extends ActionBarActivity {
private ArrayAdapter<String> adapter ;
ArrayList <ClassDetail> classesDetail ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_all);
this.bindAdapter();
ListView listView = (ListView) this.findViewById(R.id.class_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.v("Item", "clicked");
Intent intent = new Intent(view.getContext(), ShowAllClicked.class);
ClassDetail classDetail = classesDetail.get(i);
Bundle bundle = new Bundle();
bundle.putString("CLASS_NAME", classDetail.class_name);
bundle.putString("BUILDING", classDetail.building);
bundle.putString("MONDAY_START", classDetail.monday_start);
bundle.putString("MONDAY_END", classDetail.monday_end);
bundle.putString("TUESDAY_START", classDetail.tuesday_start);
bundle.putString("TUESDAY_END", classDetail.tuesday_end);
bundle.putString("WEDNESDAY_START", classDetail.wednesday_start);
bundle.putString("WEDNESDAY_END", classDetail.wednesday_end);
bundle.putString("THURSDAY_START", classDetail.thursday_start);
bundle.putString("THURSDAY_END", classDetail.thursday_end);
bundle.putString("FRIDAY_START", classDetail.friday_start);
bundle.putString("FRIDAY_END", classDetail.friday_end);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
void bindAdapter() {
DBHelper db = new DBHelper(this);
classesDetail = db.getClassesDetail();
ArrayList <String> classes = new ArrayList<>();
for(int i = 0 ; i < classesDetail.size() ; i++) {
Log.v("Adding ", classesDetail.get(i).class_name);
classes.add(classesDetail.get(i).class_name);
}
if(classes.size() == 0)
((TextView) this.findViewById(R.id.holiday)).setText(getString(R.string.noClass));
CustomArrayAdapter customArrayAdapter = new CustomArrayAdapter(classes, this);
((ListView) this.findViewById(R.id.class_list)).setAdapter(customArrayAdapter);
}
#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_show_all, 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.
return super.onOptionsItemSelected(item);
}
}
activity_show_all.xml (the xml layout of ShowAll.java)
<LinearLayout 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.android.mytimetable.ShowAll"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/class_list"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/holiday"/>
</LinearLayout>
CustomArrayAdapter.java (The custom array adapter file)
package com.example.android.mytimetable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Aman Goel on 02-08-2015.
*/
public class CustomArrayAdapter extends BaseAdapter implements ListAdapter {
private ArrayList <String> list = new ArrayList<String>();
private Context context;
public CustomArrayAdapter(ArrayList <String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
((TextView) view.findViewById(R.id.list_item)).setText(list.get(position));
Button deleteBtn = (Button) view.findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper db = new DBHelper(context);
db.deleteClass(list.get(position));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
list_item.xml (The layout of each list view)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:id="#+id/list_item"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/delete"
android:id="#+id/delete"/>
</LinearLayout>
I tried to take help from here: Set onClickListener into custom adapter and here: Where should I place the onClickListener on a Custom ListView?
However, I am still not able to make the adapter work. Any help would be appreciated
set on custom adapter getview function
TextView lst_tv=(TextView)view.findViewById(R.id.list_item);
lst_tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
customArrayAdapter.setOnItemClickListener(...)

com.example.appname has stopped unexpectedly

This is my first work on android development so I apologize in advance if the problem is one which is very minor or simple. The error I'm getting is that
com.exmaple.appname has stopped unexpectedly
My app consist of 3 java classes and 3 xml classes:
Java
DataProvider.java
MainActivity.java
MoviesAdapter.java
XML
activity_main.xml
child_layout.xml
parent_layout.xml
My code follows below:
MainActivity.class:
package com.example.expandablelist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private static final Intent Intent = null;
HashMap<String, List<String>> Movies_category;
List<String> Movies_list;
ExpandableListView Exp_list;
MoviesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
Movies_category = DataProvider.getInfo();
Movies_list = new ArrayList<String>(Movies_category.keySet());
adapter = new MoviesAdapter(this, Movies_category, Movies_list);
Exp_list.setAdapter(adapter);
}
#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 onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
DataProvide.java
package com.example.expandablelist;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider{
public static HashMap<String, List<String>> getInfo()
{
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
List<String> Action_Movies = new ArrayList<String>();
Action_Movies.add("Action Movie 1");
Action_Movies.add("Action Movie 2");
Action_Movies.add("Action Movie 3");
Action_Movies.add("Action Movie 4");
List<String> Romantic_Movies = new ArrayList<String>();
Action_Movies.add("Romantic Movie 1");
Action_Movies.add("Romantic Movie 2");
Action_Movies.add("Romantic Movie 3");
Action_Movies.add("Romantic Movie 4");
List<String> Horror_Movies = new ArrayList<String>();
Action_Movies.add("Horror Movie 1");
Action_Movies.add("Horror Movie 2");
Action_Movies.add("Horror Movie 3");
Action_Movies.add("Horro Movie 4");
List<String> Comedy_Movies = new ArrayList<String>();
Action_Movies.add("Comedy Movie 1");
Action_Movies.add("Comedy Movie 2");
Action_Movies.add("Comedy Movie 3");
Action_Movies.add("Comedy Movie 4");
MoviesDetails.put("Action Movies", Action_Movies);
MoviesDetails.put("Romantic Movies", Romantic_Movies);
MoviesDetails.put("Horror Movies", Horror_Movies);
MoviesDetails.put("Comedy Movies", Comedy_Movies);
return MoviesDetails;
}
}
MoviesAdpater.java
package com.example.expandablelist;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
public class MoviesAdapter extends BaseExpandableListAdapter{
private Context ctx;
private HashMap<String, List<String>> Movies_category;
private List<String> Movies_List;
public MoviesAdapter(Context ctx, HashMap<String, List<String>> Movies_category, List<String> Movies_List)
{
this.ctx=ctx;
this.Movies_category=Movies_category;
this.Movies_List=Movies_List;
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return Movies_List.size();
}
#Override
public int getChildrenCount(int arg0) {
// TODO Auto-generated method stub
return Movies_category.get(Movies_List.get(arg0)).size();
}
#Override
public Object getGroup(int arg0) {
// TODO Auto-generated method stub
return Movies_List.get(arg0);
}
#Override
public Object getChild(int parent, int child) {
//
return Movies_category.get(Movies_List.get(parent)).get(child);
}
//*********** Last thing I did - on video (part 2) until 7.15. **************
#Override
public long getGroupId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getChildId(int parent, int child) {
// TODO Auto-generated method stub
return child;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int parent, boolean isExpanded,
View convertView, ViewGroup parentView) {
// TODO Auto-generated method stub
String group_title = (String) getGroup(parent);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.parent_layout, parentView,false);
}
TextView parent_textview = (TextView) convertView.findViewById(R.id.parent_txt);
parent_textview.setTypeface(null, Typeface.BOLD);
parent_textview.setText(group_title);
return convertView;
}
#Override
public View getChildView(int parent, int child, boolean lastChild, View convertView, ViewGroup parentview)
{
String child_title = (String) getChild(parent, child);
if (convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.child_layout, parentview,false);
}
TextView child_textview = (TextView) convertView.findViewById(R.id.child_txt);
child_textview.setText(child_title);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return false;
}
}
activity_main.xml
<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"
android:orientation="vertical">
<ExpandableListView
android:id="#+id/exp_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#A4C739"
android:dividerHeight="0.5dp"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:layout_weight="1">
</ExpandableListView>
<Button
android:id="#+id/btnSimple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Next" />
child_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/child_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp"/>
</LinearLayout>
parent_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<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/parent_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:textColor="#A4C739"
android:paddingTop="10dp"
android:paddingBottom="10dp"/>
</LinearLayout>
I appreciate all the help I can get.
Thanks in advance.
Regards,
J
Where is your setContentView() in this code, with out layout. how you will get ListView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// add setContentView() here
Exp_list = (ExpandableListView) findViewById(R.id.exp_list);
Movies_category = DataProvider.getInfo();
Movies_list = new ArrayList<String>(Movies_category.keySet());
adapter = new MoviesAdapter(this, Movies_category, Movies_list);
Exp_list.setAdapter(adapter);
}

Items in HListView are not clickable using HorizontalListView

What I need is a Horizontal scrollable ListView that serves as a horizontally scrollable menu.
I searched for a solution and came up with the this library.
I am trying to implement it.sephiroth.android.library.widget.AdapterView.OnItemClickListener on it.sephiroth.android.library.widget.HListView object in a DialogFragment.
I can get the list to populate but I can't seem to be able to attach listeners to the item.
I have been trying for 2 days to figure this out, but no game. This feature is still not working. So I turn to the old WWW for salvation..
This is my DialogFragment XML fragment_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#800000"
android:descendantFocusability="blocksDescendants" >
<it.sephiroth.android.library.widget.HListView
android:id="#+id/hlvPlacesListScrollMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:scrollbars="none"
android:divider="#android:color/transparent"
/>
this is my viewitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#800000"
android:clickable="false"
android:focusable="false"
android:orientation="vertical" >
<ImageButton
android:id="#+id/ibScrollMenuImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#800000"
android:clickable="false"
android:focusable="false"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/tvScrollMenuTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:gravity="center_horizontal"
android:textColor="#f4f4f4" />
</LinearLayout>
This is my main_activity_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/llDialogFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#34f34f"
android:orientation="vertical"
tools:context=".MainActivity" >
</LinearLayout>
Pretty basic.
My MainActicity is :
package com.example.hscrollviewtest;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
LifeStatsDialogFragment menuFragment = new LifeStatsDialogFragment();
ft.add(R.id.llDialogFragment, menuFragment).commit();
}
#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;
}
}
the Dialogfrgment .java :
package com.example.hscrollviewtest;
import it.sephiroth.android.library.widget.AdapterView;
import it.sephiroth.android.library.widget.AdapterView.OnItemClickListener;
import it.sephiroth.android.library.widget.HListView;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LifeStatsDialogFragment extends DialogFragment implements
OnItemClickListener {
private HListView scroll;
private View rootView;
private HorizontalScrollMenuAdapter mAdapter;
final String[] IMAGE_TITLE = new String[] { "Home", "Work", "School",
"Sport" };
final int[] MENU_IMAGES = new int[] { R.drawable.ic_circle_home,
R.drawable.ic_circle_work, R.drawable.ic_circle_school,
R.drawable.ic_circle_gym };
public LifeStatsDialogFragment newInstance() {
return new LifeStatsDialogFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.fragment_layout, container, false);
mAdapter = new HorizontalScrollMenuAdapter(getActivity(),
R.layout.fragment_layout, R.id.tvScrollMenuTitle, IMAGE_TITLE,
MENU_IMAGES);
scroll = (HListView) rootView
.findViewById(R.id.hlvPlacesListScrollMenu);
scroll.setAdapter(mAdapter);
scroll.invalidate();
scroll.setOnItemClickListener(this);
for (int i = 0; i < scroll.getAdapter().getCount(); i++) {
Log.i(this.getClass().getSimpleName(), "first item in scroll : "
+ scroll.getChildAt(i) + "and its clickable?? "
+ scroll.getAdapter().getItemViewType(i) + "\n");
}
Log.i(this.getClass().getSimpleName(),
"The number of children for HlistView is: "
+ scroll.getParent().toString());
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
and this is the adapter(which works when I use it in the HorizontalVariableListViewDemo):
package com.example.hscrollviewtest;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
public class HorizontalScrollMenuAdapter extends ArrayAdapter<String>{
private String[] mButtonText;
private int[] mIconId;
private final String TAG = this.getClass().getSimpleName();
//Constructor
public HorizontalScrollMenuAdapter(Context context, int resource,
int textViewResourceId, String[] menuItemName, int[] menuItemImage) {
super(context, resource, textViewResourceId, menuItemName);
// TODO Auto-generated constructor stub
mButtonText = menuItemName;
mIconId = menuItemImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mIconId.length;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater mInflater = (LayoutInflater) parent.getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.viewitem, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.tvScrollMenuTitle);
holder.icon=(ImageButton) convertView.findViewById(R.id.ibScrollMenuImage);
//holder.icon.setBackgroundResource(android.R.color.transparent);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(mButtonText[position]);
holder.icon.setImageResource(mIconId[position]);
holder.icon.setTag(mIconId[position]);
Log.d(TAG,"returned view to fragment");
return convertView;
}
static class ViewHolder{
TextView name;
ImageButton icon;
}
}
I hope one of you can see my blindspot.
Thaks
Probably you are implementing the wrong OnItemClickListener.
Try to use
public class LifeStatsDialogFragment extends DialogFragment implements
it.sephiroth.android.library.widget.AdapterView.OnItemClickListener {
//...
}
I would try 2 things:
Put the fragment in the xml layout in the first place, and avoid add in the onCreate.
What happens in the onItemClick? - its currently empty. Try using an independent onItemClickListener:
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "clicked", Toast.LENGTH_SHORT);
}
});

Categories

Resources