Xamarin.Forms. How to add views on top of map, but right on the defined lat/lng position? - xamarin.forms

Currently i am developing a taxi app. But got to the point where i need to put some views on top of the map that will move when i move me map. I am wondering how it is possible to do it using Xamarin.Forms.GoogleMaps package. The inbuilt "Icon = BitmapDescriptorFactory.FromView()" won't work for me because i need a view that consists of two or more clickable parts + i don't want the views to overlap. Adding a picture of what i need to achieve. Any help would be appreciated
Here is the pic

Are you using Xamarin.Forms.Maps? https://www.nuget.org/packages/Xamarin.Forms.Maps/
This component makes it easier to work as you need.
In xaml file you need add this code:
>
<ContentView Content="{Binding Map}"/>
And in your viewModel add this code:
>
Map = new Map(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromKilometers(1)));
To add pins, add this:
>
var pin = new Pin
{
Type = PinType.Place,
Address = String.Empty,
Label = item.Name,
Position = new Position(item.Geometry.Location.Lat, item.Geometry.Location.Lng),
};
pin.InfoWindowClicked += async (s, args) => { await PinClicked((Pin)s); };
Map.Pins.Add(pin);

Welcome to SO !
You can create a custom renderer for the Map control, which displays a native map with a customized pin and a customized view of the pin data on each platform.
Refer to this document :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/map-pin#creating-the-custom-map
Android :
Custom the MapPlusInfo.xml in android native can achieve that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:background="#android:color/white"
android:layout_marginRight="20dp">
<TextView
android:id="#+id/InfoWindowTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowTitle"
android:textColor="#android:color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/InfoWindowSubtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="InfoWindowSubtitle"
android:textColor="#android:color/black" />
</LinearLayout>
<ImageButton
android:id="#+id/InfoWindowButton"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/plus" />
</LinearLayout>
The renderer code in Android :
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<CustomPin> customPins;
public CustomMapRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.MapPlusInfo, null);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
else
{
//view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
}
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
}
The effect :

Related

how to fix this thing in Recycler View in Kotlin Android

I am trying to display notes in my recycler view. the note body is like this:
Note Title in one text view
Note Content in the other text view below the title
So, this will get displayed in one Item and then the next note in the next item. But the issue is that,
one item is containing the note title, and the other one is containing its content.
Here is my NotesAdapter Class:
class NotesAdapter(private var noteView: ArrayList<String>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View =LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
//Set data here
holder.itemView.apply {
note_title_TV.text = noteView[position]
note_content_TV.text = noteView[position]
}
}
override fun getItemCount(): Int {
return noteView.size
}
}
My Main Activity Class (This class contains my firebase code too, as I am reading data from there and storing that into a list) :
class HomeActivity : AppCompatActivity() {
var nList = ArrayList<String>();
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
val rootReference = Firebase.database.reference //app root in firebase database
val currentUser = FirebaseAuth.getInstance().currentUser
val uid = currentUser?.uid.toString()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
//Show user's name in welcome message
//get the name of user from firebase
val nameFromFirebase: FirebaseDatabase = FirebaseDatabase.getInstance()
var nameReference = rootReference.child("users").child(uid).child("name")
nameReference.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
val result = snapshot.value
tv_User_Name.text = result.toString()
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
btn_createNote.setOnClickListener {
Intent(this, AddNoteActivity::class.java).also {
startActivity(it)
}
}
//Read notes from database
readNotesFromFirebaseDatabase()
//Updating Layout to display notes in RecyclerView
recyclerView = findViewById<RecyclerView>(R.id.rv_displayNotesInRecyclerView)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager=LinearLayoutManager(this)
//RecyclerView Adapter being passed the notes list
val adapter = NotesAdapter(nList)
rv_displayNotesInRecyclerView.adapter = adapter
}
fun readNotesFromFirebaseDatabase(){
val noteReference = rootReference.child("users").child(uid).child("Notes")
noteReference.addValueEventListener(object:ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
val noteContent = snapshot.child("noteContent").getValue(String::class.java)
val noteTitle = snapshot.child("noteTitle").getValue(String::class.java)
//Add Notes to the ArrayList of Notes
nList.add(noteTitle.toString())
nList.add(noteContent.toString())
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
Note_item XML Layout File:
<?xml version="1.0" encoding="UTF-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:id="#+id/prompt_cardview"
android:layout_width="390dp"
android:layout_height="89dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:minHeight="120dp"
app:cardCornerRadius="15dp"
app:cardElevation="3dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="384dp"
android:layout_height="match_parent"
android:minHeight="120dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/note_title_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:fontFamily="#font/lato"
android:lineHeight="22dp"
android:text="Title"
android:textAlignment="gravity"
android:textColor="#4F4B4B"
android:textSize="18sp"
android:textStyle="bold"
android:paddingLeft="2dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.037"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/note_content_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginStart="12dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="8dp"
android:fontFamily="#font/lato"
android:paddingLeft="5dp"
android:lineHeight="14dp"
android:singleLine="false"
android:text="#string/some_comments_are_here_to_stay_you_know"
android:textAlignment="center"
android:textColor=" #877B7B"
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_title_TV"
app:layout_constraintVertical_bias="0.0" />
<ImageButton
android:id="#+id/btn_edit"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/round_button_edit"
android:src="#drawable/icon_btn_edit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn_delete"
app:layout_constraintHorizontal_bias="0.972"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_content_TV"
app:layout_constraintVertical_bias="1.0" />
<ImageButton
android:id="#+id/btn_delete"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="#drawable/round_button_delete"
android:src="#drawable/icon_btn_delete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.983"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/note_content_TV"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I Also have made a Note Class (if it may be of any assistance) :
class Note (val noteContent:String , val noteTitle: String) {
}
This is my Firebase Database Note Entry, 1:https://i.stack.imgur.com/bixCW.png
Now, I am getting this output, 2: https://i.stack.imgur.com/VV7l7.png
P.S I know there are some posts regarding this like this one: How to create Multiple View Type in Recycler View but they are in Java and I am getting stuck while converting that here.
Try this:
Create a model class with 2 variables
class Notes{
val title: String = ""
val content: String = ""
}
after that creates an array list using that model class instead of String which looks like this:
val list: MutableList<Notes> = Notes()
val nots : Notes = Notes()
notes.title = "test"
notes.content = "Good Work!"
list.add(notes)
Once your list is created pass that list to adapter and you are good to go
class NotesAdapter(private var list: ArrayList<Note>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View = LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.apply {
note_title_TV.text = list[position].title
note_content_TV.text = list[position].content
}
}
override fun getItemCount(): Int {
return list.size
}
}
The problem is solved.
Change the ArrayList from String to Note
And in the Main Activity Class, edited this block of code:
//Add Notes to the ArrayList of Notes
var note : Note
note.noteContent = noteTitle.toString()
note.noteTitle = noteTitle.toString()
In the NotesAdapter Class (Posting the complete correct code):
class NotesAdapter(private var noteView: ArrayList<Note>):
RecyclerView.Adapter<NotesAdapter.MyViewHolder>() {
inner class MyViewHolder(noteView: View) : RecyclerView.ViewHolder(noteView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val noteView : View = LayoutInflater.from(parent.context).inflate(R.layout.note_card,parent,false)
return MyViewHolder(noteView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
//Set data here
holder.itemView.apply {
note_title_TV.text = noteView[position].noteContent
note_content_TV.text = noteView[position].noteTitle
}
}
override fun getItemCount(): Int {
return noteView.size
}
}

How can I make my navigation bar text bold?

I have a Master-Detail architecture, and I need to make the detail page's title text of the navigation bar bold. How can I do that the simplest way?
Here is some of my code:
private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = e.SelectedItem as MainMDPageMenuItem;
if (item == null)
return;
item.ItemBorderColor = Color.Red; // Make a red frame around the selected item
if (PreviouslySelectedItem != null)
{
PreviouslySelectedItem.ItemBorderColor = Color.FromHex("#00a8d5"); // Return the original color to the previously selected (now deselected) item
}
var page = (Page)Activator.CreateInstance(item.TargetType);
page.Title = item.Title; // THIS IS THE TITLE I AM TALKING ABOUT
Detail = new NavigationPage(page);
IsPresented = false;
MasterPage.ListView.SelectedItem = null;
PreviouslySelectedItem = item;
}
I was given a solution here:
https://forums.xamarin.com/discussion/comment/358994#Comment_358994
It is done by using TitleView:
var page = (Page)Activator.CreateInstance(item.TargetType);
var titleView = new Label
{
Text = item.Title,
FontAttributes = FontAttributes.Bold,
TextColor = Color.White,
BackgroundColor = Color.FromHex("#00a8d5")
};
NavigationPage.SetTitleView(page, titleView);
For Android part, you could implement this feature by add the following in your Resources\values\styles.xml file:
<style name="ActionBar.nameText" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textSize">58sp</item> <-- Could delete this line
<item name="android:textStyle">bold</item>
</style>
Then, add it in your Resources\layout\Toolbar.axml:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:companyApp="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"
companyApp:titleTextAppearance="#style/ActionBar.nameText"/>
For IOS, you should simply do this. in FinishedLaunching of IOS project you need to put this UINavigationBar.Appearance.TitleTextAttributes = new UIStringAttributes()
{
Font = UIFont.SystemFontOfSize(18.0f, UIFontWeight.Heavy)
};
before LoadApplication(new App());

Fragment seems to inflate wrong view

I'm currently trying to program an Android Launcher with Fragments but I have problems with the Views on the Fragments.
I have a Dock-Fragment with a Dock-Controller which allow the user to change fragments, such as apps menu, settings fragment etc. The Dock is displayed on the buttom of the display, the Fragments(apps menu, settings fragment) should be displayed above the Dock.
The problem is, that the apps menu is not shown in its associated Fragment but rather in the Dock Fragment behind the dock icons,... So I guess, the app menu fragment gets the wrong view in its onCreateView()-Method, but I don't get why.
This is the code of the MainActivity that extends from FragmentActivity. I add the fragments to the manager.
private void addDockToManager() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(dbConnection.getLayout(DOCK_TAG), dockController.getFragment(), DOCK_TAG);
ft.commit();
}
private void addPluginsToManager() {
FragmentManager fm = null;
FragmentTransaction ft = null;
for(String key : controllerMap.keySet()) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
FrameController controller = null;
if ((controller = controllerMap.get(key)) != null) {
ft.add(dbConnection.getLayout(key), controller.getFragment(), key);
if (key.equals(standardFrame))
ft.addToBackStack(key);
}
ft.commit();
fm.executePendingTransactions();
}
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
for(String key : controllerMap.keySet()) {
if (controllerMap.get(key) != null && !key.equals(standardFrame)) {
ft.hide(fm.findFragmentByTag(key));
}
}
ft.commit();
}
The layouts are hardcoded at the moment in dbConnection:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
The MainActivity's xml looks like that:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.activity.MainActivity"
tools:ignore="MergeRootFrame" >
<FrameLayout
android:id="#+id/fl_settings"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_app_menu"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_dock"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</FrameLayout>
</RelativeLayout>
The xml of the apps menu is a gridview and looks like that:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_apps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="6"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth" >
</GridView>
The App Fragment looks like that:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.external_apps, group, false);
layout = (GridView) view.findViewById(R.id.gv_apps);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GridViewAdapter gridViewAdapter = new GridViewAdapter((AppMenuController) myController, apps);
((GridView) layout).setAdapter(gridViewAdapter);
}
And the getView Method of the GridViewAdapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(controller.getMainActivity().getApplicationContext());
imageView.setImageDrawable(buttons.get(position).getIcon());
imageView.setLayoutParams(new GridView.LayoutParams(65, 65));
return imageView;
}
I hope what I mentioned is enough to resolve the problem. I am searching the web for hours but I found no solution.
It's a much simpler problem than that I think.
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
Should be:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" :
layout = R.id.fl_app_menu;
break;
case "settings" :
layout = R.id.fl_settings;
break;
case "dock" :
layout = R.id.fl_dock;
break;
}
return layout;
}
Because switch-case structure is still essentially just an organized goto, and not actually an if-else structure, aka if you don't break out, then all cases will run sequentially.
I found the problem. And it was in a part of the code I never expected it to be.
The Dummy-Switch-Case in dbConnection caused it. Seemingly Strings aren't compared by value but rather by reference in such a Switch-Case. So it always chose the dock container layout to be associated with the app menu in the fragment manager,...

Getting multiple item with one touch in GridView

I have a gridview with custom buttons called bg_button in each cell. I am trying to create a boggle-like game and still a newbie in Android. I was searching through internet about this issue over a week now and still got nothing.
The issue is, when a touch_down I can get the specific item without any problem but when I start to move diagonal, I get multiple grid items that I do not want. For example;
A O F T
K T U L
T R S V
J O K U
The grid that I have above, when I touch T and then trying to move to O, I get;
T -> J -> O or T -> R -> O
I do not want J or R, but still I am touching that as well. I have tried to change to padding, or vertical and horizontal spacing but the issue remained the same. Could you please help me about this issue or at least can you give me a way to do this, or at least a specific tag that I can google and find information that can help me? Thank you so much for your time.
This is the part of my code for the touch event. I am saving the path to an ArrayList and I am sorry for the messy code. I will clean once I finish hardcoding:
final ArrayList<Integer> myList = new ArrayList<Integer>();
gridView = (GridView) this.findViewById(R.id.gridFriends);
MyAdapter gridAdapter = new MyAdapter(Boggler.this,board_1d);
gridView.setAdapter(gridAdapter);
gridView.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
final GridView layout = (GridView)v;
int action = event.getActionMasked();
float currentXPosition = event.getX();
float currentYPosition = event.getY();
int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);
// position = layout.pointToPosition( (int)event.getX(), (int)event.getY() );
while(position == -1)
position=event.getAction();
View v2 =layout.getChildAt(position);
myList.add(position);
Bg_button bt = (Bg_button) v2.findViewById(R.id.grid_item);
bt.setPressed(true);
Log.d(this.getClass().getName(), String.format("Over view.id[%d]", position));
if (action == MotionEvent.ACTION_MOVE){
myList.add(position);
return true;
}
if (action == MotionEvent.ACTION_UP) {
Log.d(this.getClass().getName(), myList.toString());
int i=0,j=0;
int state = 0;
Object[] st = myList.toArray();
for (Object s : st) {
if (myList.indexOf(s) != myList.lastIndexOf(s)) {
myList.remove(myList.lastIndexOf(s));}
else {
v2 =layout.getChildAt(myList.get(myList.lastIndexOf(s)));
bt = (Bg_button) v2.findViewById(R.id.grid_item);
bt.setPressed(false);
name = name + bt.getText();
Log.d(this.getClass().getName(), name);
}
}
And this is the xml files that I am using button_boggler:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.proje_test.bg_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<com.example.proje_test.Bg_button
android:id="#+id/grid_item"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:clickable="false"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="#drawable/color_bg_selector"
android:textSize="50dp"
/>
</LinearLayout>
And activity_boggler:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<GridView
android:id="#+id/gridFriends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:clipChildren="true"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="4"
android:scrollbars="none"
android:stretchMode="columnWidth" >
</GridView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/feedback"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
I have found a solution that is working for me. I have seen a couple of same questions about this kind of issues without answers because of that I will answer my own question so maybe it can help those who have this kind of issues. I made custom button class with different attrs called Bg_button:
public class Bg_button extends Button {
private static final int[] STATE_C = {R.attr.state_chosen};
private static final int[] STATE_R = {R.attr.state_right};
private static final int[] STATE_W = {R.attr.state_wrong};
public boolean mIschosen = false;
public boolean mIsright = false;
public boolean mIswrong = false;
public Bg_button(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 3);
if (mIschosen) {
mergeDrawableStates(drawableState, STATE_C);
}
if (mIsright) {
mergeDrawableStates(drawableState, STATE_R);
}
if (mIswrong) {
mergeDrawableStates(drawableState, STATE_W);
}
return drawableState;
}
public void setchosen(boolean ischosen) {mIschosen = ischosen;
refreshDrawableState();}
public void setright(boolean isright) {mIsright = isright;
refreshDrawableState();}
public boolean setwrong(boolean iswrong) {mIswrong = iswrong;
refreshDrawableState();
return true;}
#Override
public void getHitRect(Rect outRect) {
outRect.set(getLeft() + 20, getTop() + 20, getRight() - 20, getBottom() - 20);
}
}
So the solution I have found is limiting the touch area of the button so they do not intercept. I don't know how ethical this is but it is working for me now.
#Override
public void getHitRect(Rect outRect) {
outRect.set(getLeft() + 20, getTop() + 20, getRight() - 20, getBottom() - 20);
}
}
This is the best answer I can come up with so far. I limited the touch area of button to its center with reversing the transaction that we do for expanding it. And the 3 lines code above did the trick. I hope this helps.

Storing Accelerometer Values

I want to develop an app which
Creates a file in external storage
2.Writes accelerometer readings to the file whenever start button is clicked
3.Stops writing when stop button is clicked
4.Reads the contents of the file on the click of read button
I don't know how to create a file in external storage and store the readings of accelerometer in it and later read the values from the file.
I tried the following code in MainACtivity.java
package com.example.startstopbuttonaccelerometerreading;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tv,tv1,tv2;
RelativeLayout layout;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title=(TextView)findViewById(R.id.name);
tv=(TextView)findViewById(R.id.xval);
tv1=(TextView)findViewById(R.id.yval);
tv2=(TextView)findViewById(R.id.zval);
}
public void onStartClick(View view) {
final SensorEventListener mySensorEventListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2]; // TODO apply the acceleration changes to your application.
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
try {
File myFile = new File("/sdcard/acc.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(acc);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'acc.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
// write on SD card file data in the text box
int sensorType = Sensor.TYPE_ACCELEROMETER;
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}// onClick
;
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
This is the activity_main.xml code :
<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"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<TextView
android:textSize="30dp"
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval"
/>
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval"
/>
</RelativeLayout>
I wrote the permission in androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity is not getting compiled. The errors are acc and textview cant be resolved.
I want to know the code to create a file in external storage and write accelerometer readings to it and read data from the file.
I have rewrote your code as the following including AndroidManifest.xml, activity_main.xml and MainActivity.java.
There are three buttons in this program.
1.Start: Start to write three-axis data into acc.txt.
2.Stop: Stop writing data.
3.Read: Read all data in acc.txt
And I create a edit text to show the content in acc.txt after the Read button is clicked.
There are some delay time in this program. You can adjust it by yourself.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.so_problem"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.so_problem.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
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"
android:id="#+id/relative" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="124dp"
android:text="Start"
android:onClick="onStartClick" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="37dp"
android:layout_toRightOf="#+id/button1"
android:text="Stop"
android:onClick="onStopClick" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_alignRight="#+id/button2"
android:layout_centerVertical="true"
android:text="Read"
android:onClick="onReadClick" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp" />
<TextView
android:textSize="20dp"
android:layout_below="#+id/name"
android:id="#+id/xval"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:textSize="20dp"
android:id="#+id/yval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/xval" />
<TextView
android:textSize="20dp"
android:id="#+id/zval"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/yval" />
<EditText
android:id="#+id/showval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/zval"
android:layout_alignRight="#+id/zval"
android:layout_below="#+id/button3"
android:layout_marginTop="18dp"
android:clickable="false"
android:cursorVisible="false"
android:editable="false"
android:ems="10"
android:freezesText="true"
android:inputType="none"
android:lines="8"
android:maxLines="1000"
android:scrollbars="vertical"
android:singleLine="false" />
</RelativeLayout>
MainActivity.java
package com.example.so_problem;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private SensorManager mSensorManager;
private Sensor mAccelerometer;
TextView title,tvx,tvy,tvz;
EditText etshowval;
RelativeLayout layout;
private String acc;
private String read_str = "";
private final String filepath = "/mnt/sdcard/acc.txt";
private BufferedWriter mBufferedWriter;
private BufferedReader mBufferedReader;
private float x;
private float y;
private float z;
public static final int MSG_DONE = 1;
public static final int MSG_ERROR = 2;
public static final int MSG_STOP = 3;
private boolean mrunning;
private Handler mHandler;
private HandlerThread mHandlerThread;
private Handler uiHandler = new Handler(){
public void handleMessage(Message msg){
String str = (String) msg.obj;
switch (msg.what)
{
case MSG_DONE:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
break;
case MSG_ERROR:
Toast.makeText(getBaseContext(),str,
Toast.LENGTH_SHORT).show();
break;
case MSG_STOP:
Toast.makeText(getBaseContext(), str,
Toast.LENGTH_SHORT).show();
default:
break;
}
super.handleMessage(msg);
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
//get layout
layout = (RelativeLayout) findViewById(R.id.relative);
//get textviews
title = (TextView)findViewById(R.id.name);
tvx = (TextView)findViewById(R.id.xval);
tvy = (TextView)findViewById(R.id.yval);
tvz = (TextView)findViewById(R.id.zval);
etshowval = (EditText)findViewById(R.id.showval);
title.setText("Accelerator");
mHandlerThread = new HandlerThread("Working Thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(r);
}
private Runnable r = new Runnable(){
#Override
public void run ()
{
while(true)
{
if (mrunning)
{
Message msg1 = new Message();
try
{
WriteFile(filepath,acc);
msg1.what = MSG_DONE;
msg1.obj = "Start to write to SD 'acc.txt'";
}
catch (Exception e)
{
msg1.what = MSG_ERROR;
msg1.obj = e.getMessage();
}
uiHandler.sendMessage(msg1);
}
else
{
Message msg2 = new Message();
msg2.what = MSG_STOP;
msg2.obj = "Stop to write to SD 'acc.txt'";
uiHandler.sendMessage(msg2);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
public void onStartClick(View view)
{
start();
}
public void onStopClick(View view)
{
stop();
}
public void onReadClick(View view)
{
etshowval.setText(ReadFile(filepath));
}
private synchronized void start()
{
mrunning = true;
}
private synchronized void stop()
{
mrunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
#Override
public void onSensorChanged(SensorEvent sensorEvent)
{
// TODO Auto-generated method stub
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
x = sensorEvent.values[0];
y = sensorEvent.values[1];
z = sensorEvent.values[2];
acc= String.valueOf(x) + ", " + String.valueOf(y) + ", " + String.valueOf(z);
tvx.setText("X = "+ String.valueOf(x));
tvy.setText("Y = "+ String.valueOf(y));
tvz.setText("Z = "+ String.valueOf(z));
}
}
public void CreateFile(String path)
{
File f = new File(path);
try {
Log.d("ACTIVITY", "Create a File.");
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String ReadFile (String filepath)
{
mBufferedReader = null;
String tmp = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedReader = new BufferedReader(new FileReader(filepath));
// Read string
while ((tmp = mBufferedReader.readLine()) != null)
{
tmp += "\n";
read_str += tmp;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return read_str;
}
public void WriteFile(String filepath, String str)
{
mBufferedWriter = null;
if (!FileIsExist(filepath))
CreateFile(filepath);
try
{
mBufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
mBufferedWriter.write(str);
mBufferedWriter.newLine();
mBufferedWriter.flush();
mBufferedWriter.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean FileIsExist(String filepath)
{
File f = new File(filepath);
if (! f.exists())
{
Log.e("ACTIVITY", "File does not exist.");
return false;
}
else
return true;
}
#Override
protected void onPause()
{
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
Toast.makeText(this, "Unregister accelerometerListener", Toast.LENGTH_LONG).show();
super.onPause();
}
}
textView.append("\nACC_x = "+ x + ", ACC_y = "+y+ ", ACC_z = " + z);
acc+="\n"+x+ ", "+ y+","+z;
You didn't declare the "textView" or "acc" variables anywhere
Even after fixing this issue, the code sample you provided above, will end in having a file with only the most recent sensor event records only.. because it creates a new file everytime a sensor event happens, writes the measurements to it, and closes it. When a new measurement is delivered a new file will be created using the same name and so will remove the old entry.
A Good practice to perform that task might be as follows:
Store the file stream as a private variable in your activity
In the start button's click event handler, open the file or create it if not existing .. and store its stream to the private variable of your activity..Also register listener to the accelerometer sensor events.
In the onSensorChanged event, append the new measurements to the file stream
In the stop button's click event handler, unregister the lisetener, and close the file stream.

Resources