I’m trying to make a ListView show multiple highlights after each item is selected, but I get strange behavior from the View. If you click on the first item, it is highlighted (after clicking the OK button on the popup window). If you click on the second item however, the last item is also highlighted. Here is the log showing that the renderer.setBackgroundResource is only called the appropriate number of times.
01-30 00:54:07.957: I/HighlightActivity(343): ListView.onItemClick: selected = 0
01-30 00:54:09.757: I/HighlightActivity(343): FINISHED_WORDS[0].equals(set)
01-30 00:54:11.387: I/HighlightActivity(343): ListView.onItemClick: selected = 1
01-30 00:54:12.757: I/HighlightActivity(343): FINISHED_WORDS[0].equals(set)
01-30 00:54:12.776: I/HighlightActivity(343): FINISHED_WORDS[1].equals(set)
If you try different selection orders, all kinds of weird behavior happens. I’m not sure if this is the best way to do this, or what the problem is. (Using Android 2.3.3 API 10)
Thanks for your help,
Curchod.
Here is the Activity:
public class HighlightActivity extends ListActivity
{
private static final String DEBUG_TAG = "HighlightActivity";
final Context context = this;
private String[] FINISHED_WORDS = {"","","","","",""};
private String[] WORDS = {"one","two","three","four","five","six"};
int selected;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.activity_highlight,
R.id.highlight_layout, WORDS)
{
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
final View renderer = super.getView(position, convertView, parent);
if (FINISHED_WORDS[position].equals("set"))
{
renderer.setBackgroundResource(android.R.color.darker_gray);
Log.i(DEBUG_TAG, "FINISHED_WORDS["+position+"].equals(set)");
}
return renderer;
}
});
ListView list_view = getListView();
list_view.setTextFilterEnabled(true);
list_view.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selected = position;
Log.i(DEBUG_TAG, "ListView.onItemClick: selected = "+selected);
final String selected_word = WORDS[position];
LayoutInflater layout_inflater = LayoutInflater.from(context);
View popup_view = layout_inflater.inflate(R.layout.highlight_popup, null);
final AlertDialog.Builder alert_dialog_builder = new AlertDialog.Builder(context);
alert_dialog_builder.setView(popup_view);
final TextView ard_player_words_popup_text = (TextView) popup_view.findViewById(R.id.highlight_popup_text);
ard_player_words_popup_text.setText(selected_word+" selected");
alert_dialog_builder.setCancelable(false).setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
FINISHED_WORDS[selected] = "set";
dialog.cancel();
ListView list_view = getListView();
ArrayAdapter<?> adapter = (ArrayAdapter<?>) list_view.getAdapter();
adapter.notifyDataSetChanged();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int id)
{
dialog.cancel();
}
});
AlertDialog alert_dialog = alert_dialog_builder.create();
alert_dialog.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_highlight, menu);
return true;
}
}
Here is the actrivity_highlight.xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/highlight_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
</RelativeLayout>
And here is the highlight_popup.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" >
<TextView
android:id="#+id/highlight_popup_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
It's possible your getView method is getting a recycled convertView, with a background already set.
Try this:
if (FINISHED_WORDS[position].equals("set"))
{
renderer.setBackgroundResource(android.R.color.darker_gray);
Log.i(DEBUG_TAG, "FINISHED_WORDS["+position+"].equals(set)");
}
else
{
renderer.setBackgroundResource(R.color.normal_background);
}
Related
I am relatively new to android and I am stuck on this problem. I created a button which launches a Dialog. The AlertDialog (to be specific) then programatically create a listView and assign an adapter to it. Now the user can click on some of the elements and the textView elements in the ListView become red. I then store the elements that were clicked. Now, when I create a dialog again, the same texts that were clicked become white.
So my question is, how do I access the listView's elements beforehand so I can alter the colour of the items that were previously clicked.
this is the java code:
private void populateListView(String[] els) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.single_listview_item,R.id.txtitem, els);
list = new ListView(this);
list.setAdapter(adapter);
list.setOnItemClickListener( new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ViewGroup vg=(ViewGroup)view;
TextView txt=(TextView)vg.findViewById(R.id.txtitem);
if(!currentList.isSelected(position)) {
txt.setBackgroundResource(R.color.redPastel);
currentList.select(position);
}
else{
txt.setBackgroundResource(R.color.white);
currentList.unselect(position);
}
}
});
}
//the listener for the button
public void showDialogListView(View view){
String [] selection = {};
Button buttonUsed = null;
switch (view.getId()){
case R.id.cuisineButton:
selection = cuisines.getArray();
currentList = cuisines;
buttonUsed = (Button) findViewById(R.id.cuisineButton);
break;
case R.id.mealTimeButton:
selection = times.getArray();
currentList = times;
buttonUsed = (Button) findViewById(R.id.mealTimeButton);
break;
}
populateListView(selection);
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
final Button finalButtonUsed = buttonUsed;
builder.setPositiveButton("Select",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finalButtonUsed.setText(currentList.getSelectionText());
}
});
builder.setNegativeButton("Cancel",null);
builder.setView(list);
AlertDialog dialog=builder.create();
dialog.show();
}
}
this is the layout of the single element XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtitem"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="25sp"
android:gravity="center"
/>
</LinearLayout>
You can get listView item like as
lv_view_task.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,final int arg2,
long arg3) {
final View selectedView v = arg1 ; // Save selected view in final variable**
AlertDialog.Builder alert=new AlertDialog.Builder(ViewTask.this);
alert.setTitle("title stackoverflow");
alert.setIcon(R.drawable.ic_launcher);
alert.setPositiveButton("Fix",new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String str=lv_view_task.getItemAtPosition(arg2).toString();
Toast.makeText(getApplicationContext(), str,Toast.LENGTH_LONG).show();
//Access view object v here
TextView label=(TextView) v.findViewById(R.id.label);
String xyz = label.getText();
}
});
I have a button and when I click that button my first custom grid view pops up as dialogue. When I click an item my second custom grid view pops up dismissing my first custom grid view. Now the problem is here, when I click an item in my second custom grid view nothing happens. My setOnItemClickListener() is not working there.I couldn't able to trace my problem where I have done wrong.
Showing my first grid view `
public void outletList() {
dialogOutlet = new Dialog(SelectCategory.this);
dialogOutlet.setContentView(R.layout.outlet_dialogue_grid);
dialogOutlet.setTitle("Select Outlet");
final GridView lv = (GridView) dialogOutlet.findViewById(R.id.gridOutletView);
oa = new OutletAdapter(this, ParseData.OutletList);
lv.setAdapter(oa);
outletFlag = 1;
lv.setOnItemClickListener(this);
dialogOutlet.show();
dialogOutlet.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
Showing second grid view `
public void billList() {
dialogueBill = new Dialog(SelectCategory.this);
dialogueBill.setContentView(R.layout.bill_dialogue_grid);
dialogueBill.setTitle("Select Bill");
final GridView bv = (GridView) dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
System.out.println("focusable "+bv.isFocusableInTouchMode());
System.out.println("focusable "+bv.findFocus());
System.out.println("Outlet Flag Bill List>>>>>>"+outletFlag);
bv.setOnItemClickListener(this);
dialogueBill.show();
dialogueBill.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
outletFlag = 0;
}
});
}`
On Item Click
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
System.out.println("Outlet Flag inside Item Click>>>>>>"+outletFlag);
if(outletFlag!=1){
HashMap<String, String> out = BillAdapter.billData.get(pos);
String sel_bill = out.get(ParseData.KEY_BILL_NO);
System.out.println("Selected Bill>>>>>>"+sel_bill);
selected_bill = sel_bill;
Intent iii = new Intent(SelectCategory.this, FBHome.class);
startActivity(iii);
}
else{
HashMap<String, String> out = OutletAdapter.outletData.get(pos);
String sel_name = out.get(ParseData.KEY_NAME);
String sel_code = out.get(ParseData.KEY_CODE);
out_pos = pos;
selected_outlet = sel_code;
selected_outlet_name = sel_name;
dialogOutlet.dismiss();
outletFlag = 0;
new GetBillDetails().execute();
}
}
Thanks in advance :)
In your Gridview Layout if you are using Clickable Widgets like Button or an ImageButton Change it and try.
That is android does not recognize click events inside the Gridadpater views, so if you change that everything should work fine
You could try
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/darker_gray"
android:layout_width="90dp"
android:layout_height="90dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/bt_grid"
android:layout_width="wrap_content"
android:textColor="#android:color/white"
android:layout_height="wrap_content" />
</LinearLayout>
Try using Alert Dialog
private void showGridDialog() {
// Prepare grid view
final GridView bv = (GridView)
dialogueBill.findViewById(R.id.gridBillView);
ba = new BillAdapter(this, ParseData.BillList);
bv.findFocus();
bv.setAdapter(ba);
bv.setFocusableInTouchMode(true);
bv.requestFocus();
bv.setClickable(true);
bv.setFocusable(true);
bv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// do something here
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(bv);
builder.setTitle("Goto");
builder.show();
}
I've an activity in which I'm showing a list of students(name, roll number) in listview.
It's actually to take attendance of students. The user clicks on listview item(which displays his name) and then a dialogbox is opened in which the student enters his password and clicks on "present" button. Whenever the student clicks on "present" button I want to disable the listview item which was just clicked. That means if the student clicks on the same listview item again then he shouldn't be allowed to do so.
It would be an immense pleasure if someone helps me out here to disable the list view item.
This is the studname_listview.xml. This is the content of the listview.
<?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/rollnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="11093"
android:textStyle="bold" />
<TextView
android:id="#+id/firstname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10sp"
android:layout_marginLeft="20dp"
android:text="roger"
android:textSize="16sp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/lastname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="federrer"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
This is the student_main.xml : This is the where the listview is there. On this listview I'm showing the contents of studmain_list_xml
<ListView
android:id="#+id/id_student_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
I'm posting the onclicklistener code I've successfully written so far which does everything I mentioned except the disabling of listview item.
this is the DisplayStudentActivity.java which gets called every time I click on any item of listview named "id_student_list".
public class DisplayStudentActivity extends Activity {
private ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student_main); // listview file name
ArrayList<HashMap<String, String>> Items = new ArrayList<HashMap<String, String>>();
// Adding Items to ListView
OverlordSimpleAdapter adapter = new OverlordSimpleAdapter(this, Items,
R.layout.studname_listview, new String[] { "firstname", "lastname", "roll" },
new int[] {R.id.firstname, R.id.lastname, R.id.rollnumber });
listView = (ListView) findViewById(R.id.id_student_list); // list view cha naav
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(DisplayStudentActivity.this);
alertDialog.setTitle(db_fname + " "+ db_lname);
alertDialog.setMessage("Enter your Password");
final EditText input = new EditText(DisplayStudentActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
alertDialog.setPositiveButton("PRESENT",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// When the control comes here i.e. "PRESENT" button is clicked, I wish to
//disable only the item of listview which was clicked to reach here.
//an anyone come up with a working code?
}
});
alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
});
alertDialog.show();
}
// inside this
}
});
db.close();
}
public class OverlordSimpleAdapter extends SimpleAdapter {
public OverlordSimpleAdapter(Context context,
List<? extends Map<String, String>> Items, int resource, String[] from,
int[] to) {
super(context, Items, resource, from, to);
// TODO Auto-generated constructor stub
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
boolean wasClicked =listView.isItemChecked(position);
view.setEnabled(!wasClicked);
return view;
}
}
}
You might want to try a ListView feature called setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
(android:choiceMode="multipleChoice" in xml)
See here: http://developer.android.com/reference/android/widget/AbsListView.html#setChoiceMode(int)
This will store a state selected/not selected per list item, and will properly refresh it when scrolling the list.
Then in your adapter's getView call setEnabled on that item according to the isItemChecked(int) state of that item.
EDIT:
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
boolean wasClicked = mListView.isItemChecked(position);
view.setEnabled(!wasClicked);
return view;
}
I've just gotten an ExpandableListView setup and everything works fine so far. On the group/parent I have a TextView and and Button. The purpose of the list is to have people sample different sounds that are included in the app, and it they click the button then the sounds will be saved to the SD Card. Here's a link to what I have so far: http://imgur.com/djSCIrG
My question is whether or not it's possible that after someone clicks the button and chooses to purchase the pack if it's possible to hide just that one button and not all of the buttons in every group.
Here's is my main layout (expandablelistview_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/soundpacktitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/expandablelistview_main_soundpacktitle_topmargin"
android:layout_centerHorizontal="true"
android:text="#string/soundpacktitle"
android:textSize="#dimen/expandablelistview_main_soundpacktitle_textsize" />
<ExpandableListView
android:id="#+id/soundpacklist"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_below="#+id/soundpacktitle"
android:layout_above="#+id/soundpackbottombar"
android:layout_marginTop="#dimen/expandablelistview_main_soundpacklist_topmargin"
android:transcriptMode="disabled"
android:cacheColorHint="#00000000"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
Here is my group/parent layout (expandablelistview_group.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal" >
<TextView
android:id="#+id/grouptextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:layout_marginLeft="#dimen/expandablelistview_group_grouptextview_leftmargin"
android:textSize="#dimen/expandablelistview_group_grouptextview_textsize" />
<Button
android:id="#+id/buypackbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignParentRight="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="#string/buypack"
android:padding="#dimen/expandablelistview_group_buypackbutton_padding"
android:textSize="#dimen/expandablelistview_group_buypackbutton_textsize"
android:textStyle="bold" />
</RelativeLayout>
Here is my java class:
public class InAppSounds extends Activity {
private ExpandableListView soundpacklist;
private ArrayList<String> groups;
private ArrayList<ArrayList<ArrayList<String>>> childs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expandablelistview_main);
TextView soundpacktitle = (TextView) findViewById(R.id.soundpacktitle);
soundpacktitle.setTypeface(printbold);
// Declare the ExpandableListView and set's the indicator to the list arrows
soundpacklist = (ExpandableListView) findViewById(R.id.soundpacklist);
soundpacklist.setGroupIndicator(getResources().getDrawable(R.drawable.list_groupselector));
LoadData();
myExpandableAdapter adapter = new myExpandableAdapter(this, groups, childs);
soundpacklist.setAdapter(adapter);
}
// Loads the ExpandableListView with parent and children groups
private void LoadData() {
groups = new ArrayList<String>();
childs = new ArrayList<ArrayList<ArrayList<String>>>();
// String array that stores the parent and child names
String[] soundpackgroups = getResources().getStringArray(R.array.soundpackgroups);
String[] soundpack1 = getResources().getStringArray(R.array.soundpack1);
String[] soundpack2 = getResources().getStringArray(R.array.soundpack2);
String[] soundpack3 = getResources().getStringArray(R.array.soundpack3);
// First Sound Pack and their songs
groups.add(soundpackgroups[0]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack1.length; a++) {
childs.get(0).add(new ArrayList<String>());
childs.get(0).get(a).add(soundpack1[a]);
}
// Second Sound Pack and their songs
groups.add(soundpackgroups[1]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack2.length; a++) {
childs.get(1).add(new ArrayList<String>());
childs.get(1).get(a).add(soundpack2[a]);
}
// Third Sound Pack and their songs
groups.add(soundpackgroups[2]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack3.length; a++) {
childs.get(2).add(new ArrayList<String>());
childs.get(2).get(a).add(soundpack3[a]);
}
}
public class myExpandableAdapter extends BaseExpandableListAdapter {
private final ArrayList<String> groups;
private final ArrayList<ArrayList<ArrayList<String>>> children;
private final Context context;
public myExpandableAdapter(Context context, ArrayList<String> groups,
ArrayList<ArrayList<ArrayList<String>>> children) {
this.context = context;
this.groups = groups;
this.children = childs;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public ArrayList<String> getChild(int groupPosition, int childPosition) {
return children.get(groupPosition).get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
String child = getChild(groupPosition, childPosition).get(0);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandablelistview_child, null);
}
// TypeFace variable for the PrintBold
printbold = Typeface.createFromAsset(getAssets(), "fonts/PrintBold.otf");
TextView childtxt = (TextView) convertView.findViewById(R.id.childtextview);
childtxt.setTypeface(printbold);
childtxt.setText(child);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return children.get(groupPosition).size();
}
#Override
public String getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final String group = getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandablelistview_group, null);
}
// TypeFace variable for the PrintBold
printbold = Typeface.createFromAsset(getAssets(), "fonts/PrintBold.otf");
TextView grouptxt = (TextView) convertView.findViewById(R.id.grouptextview);
grouptxt.setTypeface(printbold);
grouptxt.setText(group);
final Button buypackbutton = (Button) convertView.findViewById(R.id.buypackbutton);
buypackbutton.setClickable(true);
buypackbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(InAppSounds.this);
if (group.equals("Pack #1")) {
alert.setCancelable(false);
alert.setTitle(getString(R.string.buypacktitle));
alert.setIcon(getResources().getDrawable(R.drawable.ic_audioicon));
alert.setMessage(getString(R.string.buypackmsg));
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// check to make sure the SD card is mounted
// if not display an AlertDialog
if (!isSDPresent()) {
sdcardalert();
}
else {
// this will erase the button in all the groups, not just this group
buypackbutton.setVisibility(View.INVISIBLE);
}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
}
});
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
I would appreciate any guidance in this matter. Thanks
Yes. It's easy. All that you have to do is get a reference to your button and set the visibility to gone. Like this:
Button sampleButton = (Button) findViewById(R.id.sample_button);
sampleButton.setVisiblity(View.GONE);
Note: when you set it to View.GONE the layout space that was initially given to it is also removed. If you just want to remove the button and keep the layout space use
View.INVISIBLE instead.
EDIT: Here's how I would keep the button from reappearing: First, I would use a boolean to track the status of the button while the activity is active. Then in your override of getChildView I would check this boolean and set the visibility accordingly. Maybe insert something like this into the getChildView callback to keep the button from reappearing when the list item is clicked:
if (!showButton) {
Button button = (Button) findViewById(R.id.sample_button);
button.setVisibility(View.GONE);
}
As for coming back to the screen. To keep track of the whether not to show the button I would use a boolean and store it in SharedPreferences. Then, also in the getChildView callback, check the status of the boolean and set it accordingly. Something like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean showButtonStatusPref = settings.getBoolean("showButton", true);
if(!showButtonStatusPref) {
Button button = (Button) findViewById(R.id.sample_button);
button.setVisibility(View.GONE);
}
The only other thing you need to do is manage the status of each button.
EDIT 2: I completely overlooked the fact that the same layout is used for the child views (duh! brain cramp :)).
You could still use shared preferences to keep track of which samples have been downloaded (you could use Set for this). You would also need to create a way to assign "identifiers" to each sample. From there all that you would have to do is perform a check every time getChildView() is called and, if the Set contains the selected sample identifier, set the button visibility to gone. That should take care of showing the button when the sample hasn't been downloaded and not showing the button when the sample has been downloaded. Maybe something like this in the getChildView():
Set<String> defaultSet = new SortedSet<String>();
defaultSet.add("Nothing downloaded");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SortedSet<String> listOfDowloaded = settings.getStringSet("isDownloadedList", );
if (listOfDownLoaded.contains(sampleDownloadIdentifier)) {
Button button = (Button) findViewById(R.id.some_id);
button.setVisiblity(View.GONE);
}
I am trying to create a AlertDialog with multiple choice option. I have tried with the setMultiChoiceItems but what i have is a ArrayList<Category> and not a CharSequence so i tried with the adapter.
The problem with setAdapter is that when i select one item it closes the dialog window. And what i want is to select the items and then hit the OK button to see what items where selected.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
ArrayAdapter<Category> catsAdapter = new ArrayAdapter<Category>(this, android.R.layout.select_dialog_multichoice,this.categories);
builder.setAdapter(catsAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
}
});
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do something
}
});;
AlertDialog alert = builder.create();
alert.show();
Unfortunately, there doesn't seem to be an easy way to toggle on AlertDialog's multichoicemode without calling setMultiChoiceItems().
However, you can set an adapter, then turn on multichoice mode in the contained ListView itself.
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setAdapter(yourAdapter, null)
.setPositiveButton(getResources().getString(R.string.positive), null)
.setNegativeButton(getResources().getString(android.R.string.cancel), null)
.create();
dialog.getListView().setItemsCanFocus(false);
dialog.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
dialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Manage selected items here
System.out.println("clicked" + position);
CheckedTextView textView = (CheckedTextView) view;
if(textView.isChecked()) {
} else {
}
}
});
dialog.show();
this will stop ur dialog from disappearing after one selection.
AlertDialog alertDialog = builder.create();
ListView listView = alertDialog.getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
To get which items are selected , you need to plan your adapter accordingly.
see below code it may help you. i used this in my app.
public static ArrayList<String> Party_list_new = new ArrayList<String>();
ArrayList<String> party_multi_cheked = new ArrayList<String>();
public void show_alert() {
final Dialog dia = new Dialog(this);
dia.setContentView(R.layout.alert_);
dia.setTitle("Select File to import");
dia.setCancelable(true);
final ListView list_alert = (ListView) dia
.findViewById(R.id.alert_list);
list_alert.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_multiple_choice,
Party_list_new));
list_alert.setItemsCanFocus(false);
list_alert.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_alert.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
}
});
Button btn = (Button) dia.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SparseBooleanArray positions = list_alert
.getCheckedItemPositions();
int j = 0;
for (int k = 0; k < Party_list_new.size(); k++) {
if (positions.get(k)) {
party_multi_cheked.add("" + k);
}
}
dia.dismiss();
}
});
dia.show();
}
alert_list.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Party" />
<ListView
android:id="#+id/alert_list"
android:layout_width="match_parent" android:padding="5dp"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
make it right if it is correct.