TextView not updating - socket.io

I am developing a chat application using socketIO library. Every thing seems to work fine except the UI updation. I am able to send message to the port and receive from it. But after reception, i cant update textview or any other UI. the code is given below
Any help is most appreciated
NB: the toast is coming, the **updated* message is also showing when next new message comes
chatRoomActivity.java
public class chatRoomActivity extends Activity implements OnClickListener{
int channelId = 0;
public final String SocketURL = "someURL";
String userName = "";
int connectioAttempt = 0;
SocketIOClient socketClient = null;
SocketIOClientOperations sioOps = null;
Button chatRoomSend = null;
EditText chatInput = null;
TextView msgcntr;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_room);
chatRoomSend = (Button)findViewById(R.id.chatRoomSendBtn);
chatInput = (EditText)findViewById(R.id.chatRoomInput);
msgcntr=(TextView)findViewById(R.id.textView1);
chatRoomSend.setOnClickListener(this);
sioOps = new SocketIOClientOperations();
msgcntr = (TextView) findViewById(R.id.textView1);
socketClient = sioOps.connectToSocket(SocketURL);
System.out.println("**********Connected**********");
if(socketClient != null)
{
boolean joined = false;
joined = sioOps.joinChannel(socketClient, channelId);
System.out.println("*******Joined*********");
}
else
{
System.out.println("*******Null*********");
}
socketClient.on("incomingMessage", new EventCallback() {
public void onEvent(JSONArray argument, Acknowledge acknowledge) {
System.out.println("***************New Message*********");
System.out.println("***************"+argument.toString()+"*********");
msgcntr.setText("test");
updateClock();
}
});
}
#Override
public void onClick(View v) {
if(v == chatRoomSend)
{
boolean sent = sioOps.sendNewMessage(socketClient, userName, "empty");
if(sent)
System.out.println("************** Message Sent *********");
else
System.out.println("************** Message Failed *********");
}
}
protected void updateClock() {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "end", Toast.LENGTH_SHORT).show();
msgcntr.setText("test");
System.out.print("************Updated*********");
}
});
}
}
socketIOClientOperations.java
public class SocketIOClientOperations {
public SocketIOClientOperations(){}
public SocketIOClient connectToSocket(String SocketURL)
{
SocketIORequest connectionRequest = new SocketIORequest(SocketURL);
SocketIOClient socketClient = null;
try {
socketClient = SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(), connectionRequest, null).get();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
return socketClient;
}
public boolean joinChannel(SocketIOClient client,int channelId)
{
JSONArray joinChannel = new JSONArray();
JSONObject values = new JSONObject();
try {
values.put("channelID", channelId);
joinChannel.put(values);
client.emit("joinChannel", joinChannel);
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
public boolean sendNewMessage(SocketIOClient client,String name,String txt)
{
JSONArray newMsg = new JSONArray();
JSONObject msgBody = new JSONObject();
try {
msgBody.put("From", name);
msgBody.put("Content", txt);
newMsg.put(msgBody);
client.emit("newMessage", newMsg);
System.out.println("***************SendMessage*********");
System.out.println("************** "+newMsg.toString()+" *********");
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
}
chat_room.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#000"
android:padding="10dp"
android:id="#+id/header">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chat Room"
android:textColor="#fff"
android:textSize="14sp"/>
</RelativeLayout>
<ListView
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:stackFromBottom="true"
android:layout_above="#+id/footer"
android:layout_below="#+id/header"
android:id="#+id/chatRoomMsgs"
android:background="#cccccc"
android:visibility="gone" />
<TextView
android:id="#+id/msgConatainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/fooer"
android:layout_below="#+id/header"
android:background="#ccc"
android:textColor="#000" />
<RelativeLayout
android:id="#+id/fooer"
android:background="#000"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/chatRoomInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your message...."
android:layout_toLeftOf="#+id/chatRoomSendBtn"
android:layout_alignParentLeft="true"/>
<Button
android:id="#+id/chatRoomSendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:layout_alignParentRight="true" />
</RelativeLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msgConatainer"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:text="TextView"
android:textColor="#android:color/black" />
</RelativeLayout>

Try this way
private Handler mHandler = new Handler();
mHandler.post(new Runnable() {
public void run() {
msgcntr.setText("test");
}
});

Related

Update textview in android custom notification

I have a custom local notification implementing remoteview comprising of three buttons and a textview. Button click in notification changes volume of ringer but I want to increment a variable count each time the up button click or decrement then count each time downbutton click. I have problem updating textview as the broadcaster class can't access it directly. I tried a method from a post, but I can't make it work.
I get null exception at tvUpdate.text=t;
Any idea would be appreaciated. Thanks
RemoteView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="75dp"
android:weightSum="100"
android:padding="5dp"
android:background="#969696"
android:minWidth="25px"
android:minHeight="25px">
<Button
android:text="Vol_Up"
android:layout_width="0dp"
android:layout_weight="25"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textColor="#FFFFFF"
android:id="#+id/btnVolUp" />
<Button
android:text="V_Down"
android:layout_width="0dp"
android:layout_weight="25"
android:layout_margin="5dp"
android:textColor="#FFFFFF"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:id="#+id/btnVolDown" />
<Button
android:text="Silent"
android:layout_width="0dp"
android:layout_weight="25"
android:layout_margin="5dp"
android:background="#drawable/roundcnr"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:id="#+id/btnVolSilent" />
<TextView
android:text="Status"
android:layout_width="0dp"
android:layout_weight="25"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:id="#+id/tvVol" />
</LinearLayout>
Broadcaster Class
namespace RingerTest
{
[BroadcastReceiver]
public class myBroadCastR : BroadcastReceiver
{
public double counter { get; set; }
public override void OnReceive(Context context, Intent intent)
{
if(intent.Action== "VolumeUp")
{
counter += 6;
// Toast.MakeText(context,"VolumeUp",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.AdjustSuggestedStreamVolume(Adjust.Raise, Stream.Ring, VolumeNotificationFlags.PlaySound);
try
{
MainActivity.getinstance().updateTextView(counter.ToString() + "%");
}
catch (Exception ex)
{
}
}
else if (intent.Action == "VolumeDown")
{
counter -= 6;
// Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.AdjustSuggestedStreamVolume(Adjust.Lower, Stream.Ring, VolumeNotificationFlags.PlaySound);
try
{
MainActivity.getinstance().updateTextView(counter.ToString() + "%");
}
catch (Exception ex)
{
}
}
else if (intent.Action == "Silent")
{
counter = 0;
// Toast.MakeText(context, "VolumeDown",ToastLength.Long).Show();
AudioManager audioManager = (AudioManager)context.GetSystemService(Context.AudioService);
audioManager.RingerMode = RingerMode.Silent;
MainActivity.getinstance().updateTextView(counter.ToString()+"%");
}
}
}
}
MainActivity
namespace RingerTest
{
[Activity(Label = "RingerTest", MainLauncher = true)]
public class MainActivity : Activity
{
public static MainActivity ins;
private myBroadCastR myBroadl;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
ins = this;
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var myreceiver = new myBroadCastR();
var intentfilter = new IntentFilter();
intentfilter.AddAction("VolumeUp");
intentfilter.AddAction("VolumeDown");
intentfilter.AddAction("Silent");
RegisterReceiver(myreceiver, intentfilter);
Button btnNotify = FindViewById<Button>(Resource.Id.button1);
btnNotify.Click += BtnNotify_Click;
}
public static MainActivity getinstance()
{
return ins;
}
public void updateTextView(string t)
{
MainActivity.ins.RunOnUiThread(() =>
{
TextView tvUpdate = FindViewById<TextView>(Resource.Id.tvVol);
tvUpdate.Text = t;
});
}
private void BtnNotify_Click(object sender, System.EventArgs e)
{
const int requestID = 1;
//Volume Up
Intent intent_V_UP = new Intent("VolumeUp");
PendingIntent pIntent_V_UP = PendingIntent.GetBroadcast(this, requestID, intent_V_UP, PendingIntentFlags.UpdateCurrent);
//Volume Down
Intent intent_V_Down = new Intent("VolumeDown");
PendingIntent pIntent_V_Down = PendingIntent.GetBroadcast(this, requestID, intent_V_Down, PendingIntentFlags.UpdateCurrent);
//Silent
Intent intent_Silent = new Intent("Silent");
PendingIntent pIntent_Silent = PendingIntent.GetBroadcast(this, requestID, intent_Silent, PendingIntentFlags.UpdateCurrent);
Notification.Builder builder = new Notification.Builder(this);
builder.SetSmallIcon(Resource.Drawable.addContact);
/*
builder.SetContentTitle("VolControl");
builder.AddAction(Resource.Drawable.addContact, "VolDown", pIntent_V_Down);
builder.AddAction(Resource.Drawable.addContact, "VolUP", pIntent_V_UP);*/
//Custom View for Notification
RemoteViews remoteViews = new RemoteViews(this.PackageName, Resource.Layout.customNotification);
//On Button Click in CustomView
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolUp, pIntent_V_UP);
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolDown, pIntent_V_Down);
remoteViews.SetOnClickPendingIntent(Resource.Id.btnVolSilent, pIntent_Silent);
Notification notification = builder.Build();
notification.BigContentView = remoteViews;
notification.Flags = NotificationFlags.NoClear;
NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(1, notification);
}
}
}

Xamarin.Android MvvmCross Data-Binding Issue

I'm trying to create a simple app that uses the Xamarin Geofence plugin. (https://github.com/domaven/xamarin-plugins/tree/master/Geofence).
I'm using MvvmCross for model binding and the App View is interested in events coming from the Geofence instance.
On My ViewModel i have implemented the IGeofenceListener interface so that when any of the events are fired i can directly change the value of the binding properties in my ViewModel that are being targeted in the View.
public class MainViewModel : MvxViewModel, IGeofenceListener
{
double _latitude;
public double Latitude
{
get
{
return _latitude;
}
set
{
_latitude = value;
RaisePropertyChanged(() => Latitude);
}
}
double _longitude;
public double Longitude
{
get
{
return _longitude;
}
set
{
_longitude = value;
RaisePropertyChanged(() => Longitude);
}
}
string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
RaisePropertyChanged(() => Name);
}
}
public void OnAppStarted()
{
Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "App started"));
}
public void OnError(string error)
{
Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Error", error));
}
public void OnLocationChanged(GeofenceLocation location)
{
Longitude = location.Longitude;
Latitude = location.Latitude;
Name = CrossGeofence.Id;
Debug.WriteLine(string.Format("{0} - Long: {1} || Lat: {2}", CrossGeofence.Id, location.Longitude, location.Latitude));
}
public void OnMonitoringStarted(string identifier)
{
Debug.WriteLine(string.Format("{0} - Monitoring started in region: {1}", CrossGeofence.Id, identifier));
}
public void OnMonitoringStopped()
{
Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "Monitoring stopped for all regions"));
}
public void OnMonitoringStopped(string identifier)
{
Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Monitoring stopped in region", identifier));
}
public void OnRegionStateChanged(GeofenceResult result)
{
Longitude = result.Longitude;
Latitude = result.Latitude;
Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, result.ToString()));
}
}
As you can see, On certain events Im updating the properties of my ViewModel and then calling the RaisePropertyChanged event for the View.
I've added Debug tracing to ensure that these events are actually being fired.
I can see the events firing in my Output window.. and when i debug the application i can see the properties on the ViewModel been updated. It's just that the RaisePropertyChanged event in not actually updating the View.
Here is my View Code :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00007f"
android:layout_marginTop="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
local:MvxBind="Text Longitude"
android:id="#+id/textViewLongitude"
android:textColor="#android:color/white" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
local:MvxBind="Text Latitude"
android:id="#+id/textViewLatitude"
android:textColor="#android:color/white" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
local:MvxBind="Text Name"
android:textColor="#android:color/white"
android:id="#+id/textViewName" />
</LinearLayout>
This is the App setup code in my Core Library :-
public class App : MvxApplication
{
public App()
{
Mvx.RegisterSingleton<IMvxAppStart>(new MvxAppStart<MainViewModel>());
}
}
Here is the Main Activity MvxClass :-
[Activity(Label = "Geofence.Android", MainLauncher = true)]
public class MainActivity : MvxActivity<MainViewModel>
{
protected override void OnViewModelSet()
{
SetContentView(Resource.Layout.Main);
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
CrossGeofence.Initialize<MainViewModel>();
CrossGeofence.Current.StopMonitoring("LHR");
CrossGeofence.Current.StartMonitoring(new Plugin.Abstractions.GeofenceCircularRegion("Location", 54.9672132, -1.5992939, 2000)
{
NotifyOnStay = true,
NotifyOnEntry = true,
NotifyOnExit = true,
ShowNotification = true,
ShowEntryNotification = false,
ShowExitNotification = false,
ShowStayNotification = true,
NotificationStayMessage = "stay message!",
NotificationEntryMessage = "entry message!",
NotificationExitMessage = "exit message!",
StayedInThresholdDuration = TimeSpan.FromSeconds(1),
});
}
}
This is because CrossGeofence.Initialize<MainViewModel>(); creates a new ViewModel, that is not that one that was created by MvvmCross. You can see that, when you inspect the ViewModel of the activity in the debugger.
Solution
Use the GeofenceListener property.
CrossGeofence.GeofenceListener = (IGeofenceListener)ViewModel;
CrossGeofence.Initialize<MainViewModel>();

Add a toolbar in a MvxPreferenceFragmentCompat

I'm getting some problems creating a settings page using MvxPreferenceFragmentCompat. I've already shown the preferences view, but I could not include the toolbar in the same page.
I'm using XPlatformMenus sample to create my app.
I've already try many solutions like
attempt 1 or attempt 2, but no success.
Here is my current code:
SettingsFragment.cs
[MvxFragment(typeof(MainViewModel), Resource.Id.content_frame)]
[Register("myapp.droid.fragments.SettingsFragment")]
public class SettingsFragment : BasePreferenceFragment<SettingsViewModel>
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.showHamburgerMenu = true;
return base.OnCreateView(inflater, container, savedInstanceState);
}
public override void OnCreatePreferences(Bundle savedInstanceState, string rootKey)
{
this.AddPreferencesFromResource(FragmentId);
}
protected override int FragmentId
{
get
{
return Resource.Layout.fragment_settings;
}
}
}
fragment_settings.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="Title sample"
android:summary="Here is the checkbox summary"
android:defaultValue="true" />
</PreferenceScreen>
BasePreferenceFragment
public abstract class BasePreferenceFragment : MvxPreferenceFragmentCompat
{
protected Toolbar _toolbar;
protected MvxActionBarDrawerToggle _drawerToggle;
/// <summary>
/// If true show the hamburger menu
/// </summary>
protected bool showHamburgerMenu = false;
protected BasePreferenceFragment()
{
RetainInstance = true;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = base.OnCreateView(inflater, container, savedInstanceState);
_toolbar = view.FindViewById<Toolbar>(Resource.Id.toolbar);
if (_toolbar != null)
{
((MainActivity)Activity).SetSupportActionBar(_toolbar);
if (showHamburgerMenu)
{
((MainActivity)Activity).SupportActionBar.SetDisplayHomeAsUpEnabled(true);
_drawerToggle = new MvxActionBarDrawerToggle(
Activity, // host Activity
((MainActivity)Activity).DrawerLayout, // DrawerLayout object
_toolbar, // nav drawer icon to replace 'Up' caret
Resource.String.drawer_open, // "open drawer" description
Resource.String.drawer_close // "close drawer" description
);
_drawerToggle.DrawerOpened += (object sender, ActionBarDrawerEventArgs e) =>
{
if (Activity != null)
((MainActivity)Activity).HideSoftKeyboard();
};
((MainActivity)Activity).DrawerLayout.AddDrawerListener(_drawerToggle);
}
}
return view;
}
protected abstract int FragmentId { get; }
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
if (_toolbar != null && null != _drawerToggle)
{
_drawerToggle.OnConfigurationChanged(newConfig);
}
}
public override void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
if (_toolbar != null && null != _drawerToggle)
{
_drawerToggle.SyncState();
}
}
}
public abstract class BasePreferenceFragment<TViewModel> : BasePreferenceFragment where TViewModel : class, IMvxViewModel
{
public new TViewModel ViewModel
{
get { return (TViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}
}
toolbar_actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/appbar"
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
fragment_setting_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="#layout/toolbar_actionbar" />
<FrameLayout
android:id="#+id/content_frame"
android:layout_below="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
What am I doing wrong? Any idea?

How to make a Single Row Horizontal ListView/List?

What I want to do is Create a Single Row Listview/List with a image and text is this is what i have right now
I have Changed the numColumns to 1 but how do I change it so it is Horizontal and Scrollable? the image should be one top and the text should be below it?
This is the Layout
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="1"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
Single Grid Item
<?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="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:id="#+id/my_image_vieww" />
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/my_text_view" />
</LinearLayout>
Main Activity
var gridview = FindViewById<GridView> (Resource.Id.gridview);
gridview.Adapter = new ImageAdapter (this);
gridview.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) {
Toast.MakeText (this, args.Position.ToString (), ToastLength.Short).Show ();
};
public class ImageAdapter : BaseAdapter
{
Context context;
public ImageAdapter (Context c)
{
context = c;
}
public override int Count {
get { return thumbIds.Length; }
}
public override Java.Lang.Object GetItem (int position)
{
return null;
}
public override long GetItemId (int position)
{
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public override View GetView (int position, View convertView, ViewGroup parent)
{
ImageView imageView;
View view;
if (convertView == null) { // if it's not recycled, initialize some attributes
view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.my_grid_row, parent, false);
} else {
view = convertView;
}
var imageView2 = view.FindViewById<ImageView>(Resource.Id.my_image_vieww);
imageView2.SetImageResource (thumbIds[position]);
var textView = view.FindViewById<TextView>(Resource.Id.my_text_view);
textView.Text = "Text to Display";
return view;
}
}
Please Dont user horizontal list view.
There is predefined android controll to achieve this. View Pager
Sample Code:
var _viewPager = view.FindViewById<ViewPager>(Resource.Id.viewPager);
var _viewPageIndicatorCircle = view.FindViewById<CirclePageIndicator>(Resource.Id.viewPageIndicator);
_viewPager.Adapter = new TestFragmentAdapter(fm);
_viewPageIndicatorCircle.SetViewPager(_viewPager);
public class TestFragmentAdapter : FragmentPagerAdapter
{
public TestFragmentAdapter(Android.Support.V4.App.FragmentManager fm)
: base(fm)
{
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
return new TestFragment();
}
public override int Count
{
get
{
return 5;
}
}
}
class TestFragment : Android.Support.V4.App.Fragment
{
public TestFragment()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.MyViewPager , container, false);
return view;
}
}
Viewpager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="209.6dp" />
If you have any queries please feel free to ask me

Android: implementing Checkbox List with ListFragment and ArrayAdapter

I am converting a working application to Fragments. My checkbox list is not displaying the labels, and I am guessing, the id's. I am new to Android/Java and this is my first post to Stackoverflow, so apologies if the question is simple or not following correct protocol.
My ListFragment is as follows:
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class DistributionTransFragment extends ListFragment {
protected TextView subheader;
protected Context mContext;
protected DatabaseHandler db;
protected String user_id;
protected String user;
protected String recipients;
protected int number;
protected LayoutInflater inflater;
protected View v;
DistributionArrayAdapter dataAdapter = null;
public DistributionTransFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.distribution_fragment, container, false);
mContext = getActivity().getApplicationContext();
db = new DatabaseHandler(mContext);
subheader = (TextView)v.findViewById(R.id.textView2);
subheader.setText("Spent On?");
displayListView();
checkButtonClick();
return v;
}
private void displayListView() {
ArrayList<Participant> distributionList = new ArrayList<Participant>();
Participant participant;
List<User> users = db.getAllUsers();
for (User u : users) {
user_id = String.valueOf(u.getID());
user = u.getUser();
participant = new Participant(user_id, user, false);
distributionList.add(participant);
}
//create an ArrayAdaptar from the String Array
dataAdapter = new DistributionArrayAdapter(mContext, R.layout.distributionlist, distributionList);
setListAdapter(dataAdapter);
}
private class DistributionArrayAdapter extends ArrayAdapter<Participant> {
private ArrayList<Participant> distributionList;
public DistributionArrayAdapter(Context context, int textViewResourceId, ArrayList<Participant> distributionList) {
super(context, textViewResourceId, distributionList);
this.distributionList = new ArrayList<Participant>();
this.distributionList.addAll(distributionList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.distributionlist, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
Log.d("HOLDER CODE", (holder.code).toString());
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Participant participant = (Participant) cb.getTag();
participant.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Participant participant = distributionList.get(position);
holder.name.setText(participant.getName());
holder.name.setChecked(participant.isSelected());
holder.name.setTag(participant);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) v.findViewById(R.id.button1);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ArrayList<Participant> distributionList = dataAdapter.distributionList;
// Do Stuff
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(tempTransaction);
builder.setCancelable(false);
builder.setPositiveButton("Commit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do More Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do Other Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
My XML for the list is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
android:padding="15dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:textSize="15sp" />
</RelativeLayout>
My XML for the fragment is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<RelativeLayout
android:id="#+id/subheader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/secondheader"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
style="#style/subheader" />
<TextView
android:id="#+id/textView3"
style="#style/info" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/subheader"
android:layout_above="#+id/footer"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/grey"
android:layout_alignParentBottom="true" >
<Button
android:id="#+id/button1"
style="#style/button.form"
android:text="#string/moneyspent" />
</LinearLayout>
</RelativeLayout>
Any help would be greatly appreciated.
I nutted it out, so thought I would post my answer in case others have the same problem. It was my context. It should have been:
mContext = getActivity();

Resources