DialogFragments and activities, passing info - android-activity

I'm trying to show a DialogFragment asking the user his name, and I need to get back this string to my main activity.
I've created an custom dialog fragment following the android guide: http://developer.android.com/guide/topics/ui/dialogs.html#CustomLayout
In my code, in response to the user click on positive button, I am able to call a function in my main activity:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.textdialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doPositiveClick();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doNegativeClick();
}
});
return builder.create();
}
where R.layout.textdialog is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/textdraw"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="introduce text" />
</LinearLayout>
My question is, how could I get the text written by the user in my dialog fragment and send it back to my main activity?
thanks!

Well, I solved myself (but not sure if it's the better way)
I've done some changes in my onCreateDialog.
Save the view in a variable:
View v= inflater.inflate(R.layout.textdialog, null);
Save the edittext in a variable:
final EditText ed=(EditText)v.findViewById(R.id.textdraw);
Send back the value in edittext variable when the user clicks the positive button:
getActivity()).doPositiveClick(ed.getText().toString());
Full code is here:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View v= inflater.inflate(R.layout.textdialog, null);
// reference to the edittext
final EditText ed= (EditText)v.findViewById(R.id.textdraw);
builder.setView(v).setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doPositiveClick(ed.getText().toString());
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
((mainActivity)getActivity()).doNegativeClick();
}
});
return builder.create();
}
and the code in main activity:
public void doPositiveClick(String ed){
Toast.makeText(this, "Hi, "+ed, Toast.LENGTH_SHORT).show();
}

Related

How to detect backbutton/home press from a service like messenger chat head service?

I have been looking through several stackoverflow question to find out how can I listen to backpress button on a service using windows manager. Most of the answers proposes that it's not possible, however I can see that messenger handle it very well.
How does messenger handle the backpress button on it's head chat service? (Or I am completely wrong and they are not a service using windows manager?)
To achieve what you need, you need to extend some ViewGroup that you are going to use as a root container for your views. Let's start with this:
public class BackButtonAwareLinearLayout extends LinearLayout {
public interface BackButtonListener {
void onBackButtonPressed();
}
#Nullable
private BackButtonListener mListener;
public BackButtonAwareLinearLayout(Context context) {
super(context);
}
public BackButtonAwareLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BackButtonAwareLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setBackButtonListener(#Nullable BackButtonListener listener) {
mListener = listener;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK
&& mListener != null) {
mListener.onBackButtonPressed();
return true;
}
return super.dispatchKeyEvent(event);
}
}
Basically, overriding dispatchKeyEvent is what does a trick for us here.
Then make a use of it in some xml (I have called it chat_head_container.xml):
<?xml version="1.0" encoding="utf-8"?>
<com.pablo432.myapplication.BackButtonAwareLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="Hello, world!"
android:textColor="#000"
android:background="#f5f5f5"
android:gravity="center"/>
</com.pablo432.myapplication.BackButtonAwareLinearLayout>
Next, create a Service that adds our view to the WindowManager (though I suppose you know how to do it, I'll post it anyway for the sake of completeness):
public class ChatHeadService extends Service
implements BackButtonAwareLinearLayout.BackButtonListener {
private WindowManager mWindowManager;
private BackButtonAwareLinearLayout mRootContainer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRootContainer = (BackButtonAwareLinearLayout) inflater.inflate(
R.layout.chat_head_container, null, false);
mRootContainer.setBackButtonListener(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_FULLSCREEN,
PixelFormat.TRANSPARENT);
mWindowManager.addView(mRootContainer, layoutParams);
}
#Override
public void onBackButtonPressed() {
mRootContainer.setBackButtonListener(null);
mWindowManager.removeView(mRootContainer);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRootContainer != null) mWindowManager.removeView(mRootContainer);
}
}
So long story short, BackButtonAwareLinearLayout exposes a listener interface, that our service needs to implement and subscribe itself to the Layout.
Also have in mind that this addresses handling back button. To handle home button, you may want to take a look at https://stackoverflow.com/a/31340960 and https://stackoverflow.com/a/33580971 - basically my answer is a bit of a summary from those two links + https://stackoverflow.com/a/15980900 but contains few tweaks (like, for example, you can't set FLAG_NOT_FOCUSABLE in WindowManager.LayoutParams).
Of course you need to start your service somewhere by calling startService, declare this service in AndroidManifest.xml and add a SYSTEM_ALERT_WINDOW permission.

togglebutton state changes when listview is scrolled down in android?

i have placed a textview and a toggle button into a list view by using the following xml file and i have used an arrayadapter to set it on to my layout, my problem is when i scroll down in the list view by unchecking a few toggle buttons (which are all set to be checked by default), they go back to default state and few others change state. As i want to fetch the state of the toggle button in my later stages its very important to stick on to the state that ive assigned to the toggle button. Please help to resolve this problem. Here are my xml file and the java code i use to set it on to the adapter. thank you in prior...
xml file that is named listdecor is included here
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lvlistdecor"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvlistdecor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:ellipsize="marquee"
android:singleLine="true"
android:text="sample"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:typeface="sans" />
<CheckBox
android:id="#+id/cbusn_checked"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="6sp"
android:layout_weight="0.5"
android:checked="true"
android:focusable="false"
android:padding="10dp" />
</LinearLayout>
Sir i made certain changes and also included the custom adapter to the listview and also changed to CheckBox instead of toggle buttons. but now the entire list view is not visible on my emulator. i've included my edited java class and xml file, please suggest me the changes, thank you...
The modified java code is included here
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Setting the window to full screen Step 1
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); // Setting the window to full screen Step 2
setContentView(R.layout.attendance5);
facid = (TextView) findViewById(R.id.tvfacid);
facname = (TextView) findViewById(R.id.tvfacname);
subjectchosen = (TextView) findViewById(R.id.tvsubject);
// llattendlist = (LinearLayout)findViewById(R.id.llattendlist);
String Uid = getIntent().getStringExtra("Uid");
facid.setText(Uid);
String Name = getIntent().getStringExtra("Name");
facname.setText(Name);
String Sub = getIntent().getStringExtra("Sub");
subjectchosen.setText(Sub);
Attendusn = getIntent().getExtras();
if(Attendusn!=null)
{
AttendStud_usn = (ArrayList<String>)Attendusn.getStringArrayList("AttendStud_usn");
}
String AttendLen = String.valueOf(AttendStud_usn.size());
//int flag = 0 ;
//subjectchosen.setText(String.valueOf(AttendStud_usn));
myListView = (ListView) findViewById(R.id.lvnames);
// myListView.setAdapter(new ArrayAdapter<String>(this, R.layout.listdecoration,R.id.tvlistdecor, AttendStud_usn));
//ArrayAdapter<String> MyAdapter= new ArrayAdapter<String>(this,R.layout.listdecoration, R.id.tvlistdecor,AttendStud_usn);
//myListView.setAdapter(MyAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position,
long id) {
// TODO Auto-generated method stub
Stud_usn usn= MyAdapter.getItem(position);
usn.toggleChecked();
Stud_usnViewHolder vh_usn= (Stud_usnViewHolder) item.getTag();
vh_usn.getCheckBox().setChecked(usn.isChecked());
}
});
MyAdapter = new Stud_Adapter(this,AttendStud_usn);
myListView.setAdapter(MyAdapter);
}
private static class Stud_usn{
private String usn_no="";
private boolean checked=true;
public Stud_usn(String usn_no){
this.usn_no = usn_no;
}
public String getUsn(){
return usn_no;
}
public void setChecked(boolean checked){
this.checked=checked;
}
public Object isChecked() {
// TODO Auto-generated method stub
return checked;
}
public String toString(){
return usn_no;
}
public void toggleChecked() {
// TODO Auto-generated method stub
checked = !checked;
}
}
private static class Stud_usnViewHolder{
private CheckBox checkbox;
private TextView textview;
public Stud_usnViewHolder(TextView textview, CheckBox checkbox){
this.checkbox=checkbox;
this.textview=textview;
}
public CheckBox getCheckBox() {
// TODO Auto-generated method stub
return checkbox;
}
public TextView getTextView(){
return textview;
}
}
private static class Stud_Adapter extends ArrayAdapter<Stud_usn>{
public LayoutInflater inflater;
public Stud_Adapter(Context context, List<String> attendStud_usn) {
super(context,R.layout.listdecoration,R.id.tvlistdecor);
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent){
Stud_usn usn = (Stud_usn) this.getItem(position);
CheckBox checkbox;
TextView textview;
if(convertView == null){
convertView = inflater.inflate(R.layout.listdecoration,null);
textview = (TextView) convertView.findViewById(R.id.tvlistdecor);
checkbox = (CheckBox) convertView.findViewById(R.id.cbusn_checked);
}
return convertView;
}
}
}
The view objects are recycled. You have to store that info sepperately. Not in the view but in the with the data you use in the adapter. When generating the views use this info to set the button state again.
You have to implement a custom adapter. Use the BaseAdapter class.

android preferencefragment listview arrayadapter getview not called

After researching / reviewing code the past couple days, a solution eludes me. The ArrayAdapter.getView() function is not being called.
ArrayAdapter.getCount() is returning 3.
This listview is similar to the WiFi preference fragment ..
https://android.googlesource.com/platform/packages/apps/Settings.git/+/6829c48c36fceebb46989f8ee25c369fa5f7adeb/src/com/android/settings/wifi/WifiSettings.java
The code samples at GitHub (using title search terms) show that this should be working.
Queries through stackoverflow for "getView not called" have suggested that
the List was not being passed in,
the count was not being returned,
the ArrayAdapter was not attached to the ListView properly using setListAdapter vs setAdapter
the ArrayAdapter and ListView scope need to be class vs method level
the ListView may not be visible, thus android knows it would not be able to draw it on the screen so getView() method is never called to render the objects.
Provided below are the PreferenceFragment and ArrayAdapter Classes, and XML files.
Your Thoughts?
PreferenceFragment Class
public class Settings_WebServers extends PreferenceFragment
{
protected MyAdapter adapter = null;
protected ListView lv = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
addPreferencesFromResource(R.xml.settings_webservers);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView (inflater, container, savedInstanceState);
View v = inflater.inflate (R.layout.webservers, container, false);
List<String> strings = new ArrayList<String> ();
strings.add ("WebServer 1");
strings.add ("WebServer 2");
strings.add ("WebServer 3");
adapter = new MyAdapter (container.getContext(), R.layout.webservers_list, strings);
lv = (ListView) v.findViewById (android.R.id.list);
lv.setAdapter (adapter);
return v;
}
#Override
public void onStart()
{
super.onStart();;
Log.d ("onStart ", "Entered Function" );
Log.d ("ListView ", String.valueOf(lv.isShown()?"shown":"hidden"));
}
// ArrayAdapter embedded class
ArrayAdapter Class
private class MyAdapter extends ArrayAdapter<String>
{
Context context;
List<String> strings = new ArrayList<String>();
int layoutResourceId;
public MyAdapter(Context context, int layoutResourceId, List<String> objects)
{
super(context, layoutResourceId, objects);
this.layoutResourceId = layoutResourceId;
this.strings = objects;
this.context = context;
}
#Override
public int getCount ()
{ return (strings.size()); }
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
Log.d ("getView position", String.valueOf (position) );
TextView lblServerName = null;
String current = strings.get (position);
LayoutInflater inflater =
(LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate
(R.layout.webservers_list, parent, false);
lblServerName = (TextView) convertView.findViewById (R.id.txtServerName);
if (lblServerName != null)
lblServerName.setText (String.valueOf(current));
return convertView;
}
}
}
Preference Header Segment
<header
android:fragment="ENetArch.Todo.Settings_WebServers"
android:icon="#drawable/icon_server"
android:title="WebServers"
android:summary="A list of servers to synchronize with"/>
xml.settings.webservers.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
</PreferenceScreen>
layout.webservers.xml
<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="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
layout.webservers_list.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="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<TextView
android:id="#+id/txtServerName"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:text="ENetArch"
/>
</LinearLayout>
Log Trace
04-25 15:33:02.840: D/onCreateView(2941): Entered Function
04-25 15:33:02.930: D/MyAdapter(2941): construct entered
04-25 15:33:02.930: D/MyAdapter(2941): construct exited
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/getCount(2941): 3
04-25 15:33:02.950: D/onCreateView(2941): Exiting Function
04-25 15:33:03.070: D/onStart(2941): Entered Function
04-25 15:33:03.070: D/ListView(2941): hidden

Video customview in full screen exits when toggling the device screen in android

I am developing an android application which is purely web based. It needs to display HTML5 based webpages using webview which is rich in multimedia contents. when I try to play video content embedded in the webpage its all gone fine and i am also able to play video in full screen.
But my main problem starts here: When I toggled the device screen while playing fullscreen video, it suddenly exits from playback to its current web page. I am stucked here and here I am including all codes that I used as I can in hopes someone can help me.
Activity that is used: MainActivity.java
`
public class MainActivity extends Activity {
private WebView webView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private MyWebViewClient mWebViewClient;
private MyWebChromeClient mWebChromeClient;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
webView = (WebView) findViewById(R.id.webView);
mWebViewClient = new MyWebViewClient();
webView.setWebViewClient(mWebViewClient);
mWebChromeClient = new MyWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(true);
webView.loadUrl("http://yuotube.com");
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
webView.onPause();
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
webView.onResume();
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
if (inCustomView()) {
hideCustomView();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inCustomView()) {
hideCustomView();
return true;
}
if ((mCustomView == null) && webView.canGoBack()) {
webView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
// WebChromeClient Class
public class MyWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
#Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
onShowCustomView(view, callback); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onShowCustomView(View view,CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomView = view;
webView.setVisibility(View.GONE);
customViewContainer.setVisibility(View.VISIBLE);
customViewContainer.addView(view);
customViewCallback = callback;
}
#Override
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
}
return mVideoProgressView;
}
#Override
public void onHideCustomView() {
super.onHideCustomView(); //To change body of overridden methods use File | Settings | File Templates.
if (mCustomView == null)
return;
webView.setVisibility(View.VISIBLE);
customViewContainer.setVisibility(View.GONE);
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
customViewContainer.removeView(mCustomView);
customViewCallback.onCustomViewHidden();
mCustomView = null;
}
}
// WebViewClient Class
public class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url); //To change body of overridden methods use File | Settings | File Templates.
}
ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "",
"Loading multimedia! Please wait...", true);
#Override
public void onPageFinished(WebView view, String url) {
dialog.dismiss();
}
}
}
web_activity.xml
<!-- View that will be hidden when video goes fullscreen -->
<RelativeLayout
android:id="#+id/nonVideoLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.iptvmodified.VideoEnabledWebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<!-- View where the video will be shown when video goes fullscreen -->
<RelativeLayout
android:id="#+id/videoLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- View that will be shown while the fullscreen video loads (maybe include a spinner and a "Loading..." message) -->
<View
android:id="#+id/videoLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible" />
</RelativeLayout>
`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" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
I am searching for a solution for thisand googled this to death with no progress made. Any help would be greatly appreciated.
Normally when the device is rotated your activity gets destroyed and recreated. This is probably causing the WebView to get 'kicked out of' fullscreen playback.
You need to override Activity.onConfigurationChanged and declare you want to handle orientation changes in your manifest. See the docs for details.

Programmatically change listview so that it is checkable

I've made a decent effort to find a similar question and failed, so please forgive me if this is redundant pollution.
I have a ListView and an ImageButton defined in the xml file "my_layout" corresponding to my Activity as follows:
<ListView
android:id="#+id/listViewItems"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
></ListView>
and
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/btn_delete_dark"
android:id="#+id/buttonDelete"
android:layout_weight="1">
</ImageButton>
I then populate the ListView programmatically in the onCreate() method of my Activity as follows:
public class ViewItemsActivity extends Activity implements OnClickListener,
OnItemClickListener{
ImageButton buttonDelete;
ListView listViewItems;
DatabaseHandler dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
buttonDeleteQuestion = (ImageButton) findViewById(R.id.buttonDelete);
listViewQuestions = (ListView) findViewById(R.id.listViewItems);
buttonDelete.setOnClickListener(this);
//get data from sql table containing items
dbHandler = new DatabaseHandler(this);
String [] items = dbHandler.getItems(); //get data to populate ListView
CustomAdapter adapter = new CustomAdapter(this,
android.R.layout.simple_list_item_1, items);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonDelete:
listViewItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewItems.setItemChecked(0, true);
break;
//other cases are irrelevant
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
// TODO Auto-generated method stub
//non relevant code
}
}
Everything works as it should except that I want the ListView to change, in appearance and functionality, as a result of clicking buttonDelete, so that it displays checkmarks to the right of each row which can be checked by clicking on them.
It was my understanding that setChoiceMode(ListView.MULTIPLE_CHOICE) and setItemChecked(i,true) would have this effect, but clearly I've missed something as it does not.
I am quite new to android and so it is possible that I've wasted someone's time with trivialities, for which I apologize.
Thank you very much.
The solution was really simple, and is the following:
in the onClick event corresponding to buttonDelete, I simply created a new adapter whose layout id is *simple_list_item_multiple_choice* and assigned it to the ListView with the lines
CustomAdapter adapter = new CustomAdapter(this,
android.R.layout.simple_list_item_multiple_choice, items);
listViewItems.setAdapter(adapter);
which did the trick.