How do i go about making a drop down in android - android

before input
barcode: ____________
QTY: ________________
after input
when barcode has detect the input consist records
barcode:______apple______
+ apple1 + apple2 +apple3 +apple4
QTY:______________________
The + is a clickable circle button.
What method do you suggest. drop down? but wont the both QTY be affected??

You can use Android PopupWindow show as dropdown list
see in this links http://rajeshandroiddeveloper.blogspot.in/2013/07/android-popupwindow-example-in-listview.html
android.widget.PopupWindow can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.
I am going to explain how to use popupwindow in list view. For example in listview item you have details button means you can use this popupwindow to show those details in this window. Lets see how to do it.
Step 1 : Main.xml
You can use either list view or any other Composite listviews:
<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=".MainActivity" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="vertical"
>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</RelativeLayout>
Step 2 : listviewchild.xml
You can design your own custom view.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_item"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:gravity="right"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/textview_name"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Step 3 :
Your MainActivity.java
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class MainActivity extends Activity {
String TAG = "MainActivity.java";
String popUpContents[];
PopupWindow popupWindowDogs;
ListView listView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1=(ListView)findViewById(R.id.listView1);
listView1.setAdapter(new MyAddapter(MainActivity.this)); // binding the list view.
/*
* initialize pop up window items list
*/
// add items on the array dynamically
// format is Company Name:: ID
List<String> dogsList = new ArrayList<String>();
dogsList.add("Samsung");
dogsList.add("Google");
dogsList.add("Yahoo");
dogsList.add("Microsoft");
// convert to simple array
popUpContents = new String[dogsList.size()];
dogsList.toArray(popUpContents);
/*
* initialize pop up window
*/
popupWindowDogs = popupWindowDogs();
}
/*
*
*/
public PopupWindow popupWindowDogs() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewDogs = new ListView(this);
// set our adapter and pass our pop up window contents
listViewDogs.setAdapter(dogsAdapter(popUpContents));
// set the item click listener
listViewDogs.setOnItemClickListener(new DogsDropdownOnItemClickListener());
// some other visual settings
popupWindow.setFocusable(true);
popupWindow.setWidth(250);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the list view as pop up window content
popupWindow.setContentView(listViewDogs);
return popupWindow;
}
/*
* adapter where the list values will be set
*/
private ArrayAdapter<String> dogsAdapter(String dogsArray[]) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dogsArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String text = getItem(position);
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
listItem.setTag(position);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
return adapter;
}
}
Step 4:
Your Adapter class
class MyAddapter extends BaseAdapter {
Context rContext;
private LayoutInflater rInflater;
private Activity activity;
public MyAddapter(Context c) {
rInflater = LayoutInflater.from(c);
rContext = c;
}
public MyAddapter(Activity imagebinding) {
// TODO Auto-generated constructor stub
activity = imagebinding;
rContext = imagebinding;
rInflater = LayoutInflater.from(imagebinding);
rContext = imagebinding;
rInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 10;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
convertView = rInflater.inflate(R.layout.child, null);
final MyDat mydat = new MyDat();
mydat.imageView1=(ImageView)convertView.findViewById(R.id.imageView1);
mydat.imageView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindowDogs.showAsDropDown(v, -5, 0);
}
});
return convertView;
}
class MyDat {
ImageView imageView1;
}
}
Step 5 :
Your Popup Windows items Click listener
You can use this if you want proceed furtherly for activity transitions.
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class DogsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
// get the context and main activity to access variables
Context mContext = v.getContext();
MainActivity mainActivity = ((MainActivity) mContext);
// add some animation when a list item was clicked
Animation fadeInAnimation = AnimationUtils.loadAnimation(v.getContext(), android.R.anim.fade_in);
fadeInAnimation.setDuration(10);
v.startAnimation(fadeInAnimation);
// dismiss the pop up
mainActivity.popupWindowDogs.dismiss();
// get the text and set it as the button text
Toast.makeText(mContext, "Selected Positon is: " + arg2, 100).show();
}
}

Related

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(...)

show/hide button when focus the list item in android listview

Many list items are listed in my listview.
In that list item having 2 buttons and one textview.
Here i have using following code. Now my list showing the edit/delete button.If I have to focus which list item means that item alone have to show edit/delete button.other list item don't need to show the edit/delete button.
How can i do ? Please check it and give me a idea to implement this part ?
stafflist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
Button bPrevious = (Button)view.findViewById(R.id.view_staff);
bPrevious.setVisibility(View.VISIBLE);
Button bPlaying = (Button)view.findViewById(R.id.delete_staff);
bPlaying.setVisibility(View.VISIBLE);
}
});
Now if i have selected any item from that list means it's showing the edit/delete button. after that i have selected any other item from list means that item also showing the edit/delete button with this previous selected item also showing the edit/delete button.
But i want to show the current selected item only need to show edit/delete button ?
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.manager_list_staff, null);
TextView staffname = (TextView)vi.findViewById(R.id.my_staffname);
TextView staff_empcode = (TextView)vi.findViewById(R.id.my_staffempcode);
LinearLayout editdelete = (LinearLayout)vi.findViewById(R.id.edit_delete);
final Button edit_staff = (Button)vi.findViewById(R.id.view_staff);
final Button delete_staff = (Button)vi.findViewById(R.id.delete_staff);
HashMap<String, String> Order = new HashMap<String, String>();
Order = data.get(position);
int temp = parent.getId()+1;
staff_id.setText(Order.get(Manager_List_Staff.TAG_STAFF_ID));
I tested with the below code and its working, you could check with your requirement. The notifyDataSetChanged() method is used to tell the adapter that the arraylist values are changed so please reload the list so now we got the selected item and we will keep it's VISIBLE state to true and others to GONE.
MainActivity
package com.example.test;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemClickListener
{
ListView listview;
testAdapter adp;
ArrayList<String> testvalues=new ArrayList<String>();
public static int selectedValue=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView) findViewById(R.id.listView1);
testvalues.add("India");
testvalues.add("USA");
testvalues.add("Australia");
listview.setOnItemClickListener(this);
adp=new testAdapter();
listview.setAdapter(adp);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
Button bPrevious = (Button)arg1.findViewById(R.id.button1);
bPrevious.setVisibility(View.VISIBLE);
Button bPlaying = (Button)arg1.findViewById(R.id.button2);
bPlaying.setVisibility(View.VISIBLE);
selectedValue=arg2;
adp.notifyDataSetChanged();
}
class testAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return testvalues.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return testvalues.get(arg0);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.testing, null);
TextView staffname = (TextView)vi.findViewById(R.id.textView1);
final Button edit_staff = (Button)vi.findViewById(R.id.button1);
final Button delete_staff = (Button)vi.findViewById(R.id.button2);
staffname.setText(testvalues.get(position));
if(selectedValue==position && selectedValue!=-1)
{
edit_staff.setVisibility(View.VISIBLE);
delete_staff.setVisibility(View.VISIBLE);
}
else
{
edit_staff.setVisibility(View.GONE);
delete_staff.setVisibility(View.GONE);
}
return vi;
}
}
}
Main Activity XML Layout File (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: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=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="500dp" >
</ListView>
</RelativeLayout>
Inflate XML Layout File (testing.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="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
Use member variable to store the button. In my case, I'm using Layout to display some text along with button. So I'm changing the view of the inner layout of list item.
View hiddenLayout;
Attach listener to the listView. Before hiding the view / layout, verify if it is visible or not.
myList.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(hiddenLayout != null && hiddenLayout.getVisibility() == View.VISIBLE)
hiddenLayout.setVisibility(View.GONE);
hiddenLayout = view.findViewById(R.id.myTripBbuttonLayout);
hiddenLayout.setVisibility(View.VISIBLE);
}
});
In your onClickItem listener you need to define and find your button. Here is an example:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int btnStart = R.id.btnStart;
int btnDelete = R.id.btnDelete;
//here set all button in item invisible
for (int i = 0; i < parent.getChildCount(); i++) {
parent.getChildAt(i).findViewById(btnStart).setVisibility(View.INVISIBLE);
parent.getChildAt(i).findViewById(btnDelete).setVisibility(View.INVISIBLE);
parent.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
//but here we set for selected item buttons visible, and change background view.setBackgroundColor(getResources().getColor(R.color.color_selected_nav_drawer));
view.findViewById(btnStart).setVisibility(View.VISIBLE);
view.findViewById(btnDelete).setVisibility(View.VISIBLE);
}

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);
}
});

How to maintain the clicked item highlighted in Listview?

I need to make a listview keep the selected view highlighted until another item is chosen, in that case the previous view removes the highlight and the latest clicked gets the highlight.
I tried not to do this and with a radio button but it isnt working.
It's actually pretty easy:
In the custom layout for the individual listview item, make sure it has the attribute:
android:background="?android:attr/activatedBackgroundIndicator" >
By way of example, here's a listview item layout from the HoneycombGallery sample that ships with the SDK (located in the title_list_item.xml file:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:gravity="bottom"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="?android:attr/activatedBackgroundIndicator" >
</TextView>
That attribute will cause the background color to change based on whether the individual list item is selected or not.
i m novice to android so i found this question interesting and finally i succeeded after 1 and half hour ;-)
here is the code:
main.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="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
listinflater.xml
android:id="#+id/tvItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
PreservelistitemActivity.java
package com.mehuljoisar;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class PreservelistitemActivity extends Activity {
//declaring variable
ListView listView1;
MyAdapter adapter1;
Integer length,i;
String[] data = {"Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//binding to the view
listView1 = (ListView)findViewById(R.id.listView1);
//set adapter
adapter1=new MyAdapter(PreservelistitemActivity.this,data);
listView1.setAdapter(adapter1);
}
public class MyAdapter extends BaseAdapter{
private final Activity context;
private final String[] data;
public MyAdapter(Activity context,
String[] data) {
// TODO Auto-generated constructor stub
super();
this.context=context;
this.data=data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.listinflater, null);
final TextView tvItem = (TextView)convertView.findViewById(R.id.tvItem);
tvItem.setText(data[position]);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
/* length=parent.getAdapter().getCount();
for(i=0;i<length;i++)
{
//clear
if(i==position)
{
//set
}
}
*/
v.setSelected(true);
}
});
return convertView;
}
}
}

Android how to identify item in listview with checkbox

I am really stuck here. What I want is not simple (for me), however I've been programming android a year now.
What I want is a listview with an imageview, a textview, a checkbox, and another textview in each row.
Let's have a textview and a checkbox first in the layout.
Based on this tutorial I managed to do that (there are a lot, but this seems to be the best for me). I have a listview populated with textviews and checkboxes.
This is the result:
This is how I get the text of textview I click on:
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v ;
String text_of_clicked_textview = tv.getText().toString();
Log.i("TAG", "" + text_of_clicked_textview);
}
});
So When I click on Mercury, I get Mercury in the text_of_clicked_textview variable.
But how can i check which checkbox I clicked on? E.g I click on the 3rd checkbox, I want to now it is in the row of Earth. Best would be if I get to know both the text of textview in the row of the listview(Earth) and and number of the item (3).
I guess I have to set an onClickListener on the checkbox but what next?
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
}
});
This is XML for Custom Row in ListView :
<?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="fill_parent">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/camera_icon" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
This is Complete Activity in which List is implemented :
Just Copy this Activity for test then understand code. Place one listview in main Activity
package com.DemoTest;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomList extends Activity implements OnClickListener
{
ListView listView;
ArrayList<EachRow> list=new ArrayList<CustomList.EachRow>();
EachRow each;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] color={"red","green","blue","white","yellow","cyan","purple","grey",
"0red","0green","0blue","0white","0yellow","0cyan","0purple","0grey",
"1red","1green","1blue","1white","1yellow","1cyan","1purple","1grey"};
for(String str : color)
{
each=new EachRow();
each.text=str;
list.add(each);
}
listView=(ListView)findViewById(R.id.listView1);
listView.setAdapter(new MyAdapter(this, 0, list));
//listView.setOnItemClickListener(this);
}
class MyAdapter extends ArrayAdapter<EachRow>
{
LayoutInflater inflat;
ViewHolder holder;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<EachRow> objects)
{
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
inflat=LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
convertView=inflat.inflate(R.layout.row_checkox, null);
holder=new ViewHolder();
holder.textView=(TextView)convertView.findViewById(R.id.textView1);
holder.image=(ImageView)convertView.findViewById(R.id.imageView1);
holder.check=(CheckBox)convertView.findViewById(R.id.checkBox1);
holder.check.setOnClickListener(CustomList.this);
convertView.setTag(holder);
}
holder=(ViewHolder) convertView.getTag();
EachRow row= getItem(position);
Log.d("size", row.text);
holder.textView.setText(row.text);
holder.check.setChecked(row.checkBool);
holder.check.setTag(position);
return convertView;
}
#Override
public EachRow getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
private class ViewHolder
{
TextView textView;
ImageView image;
CheckBox check;
}
}
private class EachRow
{
String text;
boolean checkBool;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
EachRow row=list.get((Integer)v.getTag());
row.checkBool=!row.checkBool;
Log.d("item", "Item Click at "+(Integer)v.getTag()+" : "+row.text+" is "+row.checkBool);
}
}
Better than adding an onClickListener to each checkbox, you could also use an ItemClickListener on your list.
Refer to this post to find out the row that has been clicked :
onItemClick <string-array> strings.xml (not ListView/ArrayList)
There are other options, but it involves creating a custom row widget class, and passing it its row position when your adapter creates or updates it.
you would have to have a onTouchListener on the container that holds all of them and make sure that you return false on your listeners so that they don't consume the event. onClickListener consumes it automatically.
If you only concerned with text and checkbox then you can use this
In XML :
<ListView
android:id="#+id/listViewCursor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" >
String[] color={"red","green","blue","white","yellow","cyan","purple","grey"};
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, color));
ANd on some event check which checkboxes are selected.
SparseBooleanArray boolArray=list.getCheckedItemPositions();
int size=list.getCount();
for(int i=0;i<size;i++)
{
if(boolArray.valueAt(i)==true)
{
Log.d("size", color[i]);
}
}

Categories

Resources