问:
Xamarin.Forms How to two-way bind to a control in Listview
Im having a hard time trying to figure out how to set up a two-way binding for a control inside a listview.

Im using ReactiveUI and Xamarin.Forms.

In this case i would like to load a list of objects that have a quantity. This is set initially when the page loads. However i would like to be able to change these quantity values in the view when the program is run. I used an Entry for that.

Setting up a two-way Binding for the List itself (done in code behind, the reactive way) is not possible. It will error.

Is there another way to observe changes done to the Text property in the Entry control and reflect them to the according item from the list in my viewmodel?

I've been having trouble finding a solution for this and don't really know how to go about this.

Here is my XAML code:

```<code><CustomControls:AutoLoadListView.ItemTemplate>
       <DataTemplate>
               <ViewCell>
                        <StackLayout Margin="20,0,0,0" Orientation="Vertical" HorizontalOptions="StartAndExpand">
                            <Label Margin="0,5,0,-5" Style="{StaticResource ViewCellPrimaryLabelStyle}"   x:Name="txt" Text="{Binding itemname}" />
                            <Label Margin="0,-5,0,5" Style="{StaticResource ViewCellSecondaryLabelStyle}" x:Name="barcode" Text="{Binding productcode}" />
                        </StackLayout>
                        <Entry Margin="5,0,5,0" x:Name="quantity" Text="{Binding quantity}">
                             <Entry.BindingContext>
                                 <ViewModel:AankoopEditViewModel />
                             </Entry.BindingContext>
                        </Entry>
                        <Image Margin="5,5,5,5" x:Name="delete"  Source="{Mobile:ImageResource tbin_pos.png}">
                             <Image.GestureRecognizers>
                                 <TapGestureRecognizer
                                  Command="{Binding Path=BindingContext.DeleteCommand,Source={x:Reference Name=AankoopEditPage}}"
                                  CommandParameter="{Binding}" />
                             </Image.GestureRecognizers>
                        </Image>
                </ViewCell>
        </DataTemplate>
</CustomControls:AutoLoadListView.ItemTemplate>
</code>```

My Viewmodel:

```<code>public class AankoopEditViewModel : BaseViewModel
{

    private VmPurchase Purchase;

    public AankoopEditViewModel()
    {

        PurchaseList = new ReactiveObservableCollection<AankoopEditListItem>()
        {
            ChangeTrackingEnabled = true
        };

        this.WhenAnyValue(x => x.PurchaseID).SubscribeOn(RxApp.MainThreadScheduler).Subscribe((x) =>
        {
            this.Purchase = DatabaseHelper.Purchase.LoadSingleById<VmPurchase>(PurchaseID);

            if (Purchase != null)
            {
                this.Title = Purchase.supplier.name;

                using (PurchaseList.SuppressChangeNotifications())
                {
                    foreach (var detail in Purchase.purchasedetails)
                    {
                        PurchaseList.Add(new AankoopEditListItem { productcode = detail.item.code, itemname = detail.item.namenl, identifier = detail.key, quantity = detail.quantity.ToString() });

                    }
                }
            }
        });

        try
        {
            this.WhenAnyValue(x => x.PurchaseList).SubscribeOn(RxApp.MainThreadScheduler).Subscribe((x) =>
            {
                Console.WriteLine("The List has changed");
            });
        }
        catch (Exception e)
        {
            return;
        }
    }

    private string _purchaseID;

    public string PurchaseID
    {
        get { return _purchaseID; }
        set { this.RaiseAndSetIfChanged(ref _purchaseID, value); }
    }

    private ReactiveObservableCollection<AankoopEditListItem> _purchases;

    public ReactiveObservableCollection<AankoopEditListItem> PurchaseList
    {
        get
        {
            return this._purchases;
        }
        set
        {
            this.RaiseAndSetIfChanged(ref _purchases, value);
        }
    }
</code>```

My Model :

```<code>public class AankoopEditListItem : ReactiveObject
{
    public string identifier { get; set; }
    public string itemname { get; set; }
    public string productcode { get; set; }
    public string quantity { get; set; }
}
</code>```

答:
Be careful, when you do this

```<code><Entry.BindingContext>
   <ViewModel:AankoopEditViewModel />
</Entry.BindingContext>
</code>```

you create a new instance of your view model for each item and you bind your Entry to it. Just remove it and keep the binding as it is (Text="{Binding quantity}") if you want to bind your entry to the row view model

Body:
Im having a hard time trying to figure out how to set up a two-way binding for a control inside a listview.

Im using ReactiveUI and Xamarin.Forms.

In this case i would like to load a list of objects that have a quantity. This is set initially when the page loads. However i would like to be able to change these quantity values in the view when the program is run. I used an Entry for that.

Setting up a two-way Binding for the List itself (done in code behind, the reactive way) is not possible. It will error.

Is there another way to observe changes done to the Text property in the Entry control and reflect them to the according item from the list in my viewmodel?

I've been having trouble finding a solution for this and don't really know how to go about this.

Here is my XAML code:

<CustomControls:AutoLoadListView.ItemTemplate>
       <DataTemplate>
               <ViewCell>
                        <StackLayout Margin="20,0,0,0" Orientation="Vertical" HorizontalOptions="StartAndExpand">

                        </StackLayout>
                        <Entry Margin="5,0,5,0" x:Name="quantity" Text="{Binding quantity}">
                             <Entry.BindingContext>
                                 <ViewModel:AankoopEditViewModel />
                             </Entry.BindingContext>
                        </Entry>
                        <Image Margin="5,5,5,5" x:Name="delete"  Source="{Mobile:ImageResource tbin_pos.png}">
                             <Image.GestureRecognizers>
                                 <TapGestureRecognizer
                                  Command="{Binding Path=BindingContext.DeleteCommand,Source={x:Reference Name=AankoopEditPage}}"
                                  CommandParameter="{Binding}" />
                             </Image.GestureRecognizers>
                        </Image>
                </ViewCell>
        </DataTemplate>
</CustomControls:AutoLoadListView.ItemTemplate>

My Viewmodel:

public class AankoopEditViewModel : BaseViewModel
{

    private VmPurchase Purchase;

    public AankoopEditViewModel()
    {

        PurchaseList = new ReactiveObservableCollection<AankoopEditListItem>()
        {
            ChangeTrackingEnabled = true
        };

        this.WhenAnyValue(x => x.PurchaseID).SubscribeOn(RxApp.MainThreadScheduler).Subscribe((x) =>
        {
            this.Purchase = DatabaseHelper.Purchase.LoadSingleById<VmPurchase>(PurchaseID);

            if (Purchase != null)
            {
                this.Title = Purchase.supplier.name;

                using (PurchaseList.SuppressChangeNotifications())
                {
                    foreach (var detail in Purchase.purchasedetails)
                    {
                        PurchaseList.Add(new AankoopEditListItem { productcode = detail.item.code, itemname = detail.item.namenl, identifier = detail.key, quantity = detail.quantity.ToString() });

                    }
                }
            }
        });

        try
        {
            this.WhenAnyValue(x => x.PurchaseList).SubscribeOn(RxApp.MainThreadScheduler).Subscribe((x) =>
            {
                Console.WriteLine("The List has changed");
            });
        }
        catch (Exception e)
        {
            return;
        }
    }

    private string _purchaseID;

    public string PurchaseID
    {
        get { return _purchaseID; }
        set { this.RaiseAndSetIfChanged(ref _purchaseID, value); }
    }

    private ReactiveObservableCollection<AankoopEditListItem> _purchases;

    public ReactiveObservableCollection<AankoopEditListItem> PurchaseList
    {
        get
        {
            return this._purchases;
        }
        set
        {
            this.RaiseAndSetIfChanged(ref _purchases, value);
        }
    }

My Model :

public class AankoopEditListItem : ReactiveObject
{
    public string identifier { get; set; }
    public string itemname { get; set; }
    public string productcode { get; set; }
    public string quantity { get; set; }
}

Body:
Be careful, when you do this

<Entry.BindingContext>
   <ViewModel:AankoopEditViewModel />
</Entry.BindingContext>

you create a new instance of your view model for each item and you bind your Entry to it. Just remove it and keep the binding as it is (Text="{Binding quantity}") if you want to bind your entry to the row view model


来源: stackexchange

问:
Dialogic ADPCM VOX file 6000 Hertz to Wave GSM in Alvas.Audio
How to convert Dialogic ADPCM VOX file 6000 samples per second to Wave GSM in Alvas.Audio?</p>

答:
Please see example and code below</p>

```<code>private static void Vox2Gsm(string voxFile, string wavFile)
{
    int samplesPerSec = 6000;
    IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);
    MemoryStream ms = new MemoryStream();
    BinaryReader br = new BinaryReader(File.OpenRead(voxFile));
    WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));
    Vox.Vox2Wav(br, ww);
    br.Close();
    WaveReader wr = new WaveReader(ms);
    byte[] data = wr.ReadData();
    wr.Close();
    ww.Close();
    IntPtr formatGsm = AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.Gsm610FormatTag);
    byte[] dataGsm = AudioCompressionManager.Convert(format, formatGsm, data, false);
    WaveWriter wwGsm = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(formatGsm));
    wwGsm.WriteData(dataGsm);
    wwGsm.Close();
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Please see example and code below

private static void Vox2Gsm(string voxFile, string wavFile)
{
    int samplesPerSec = 6000;
    IntPtr format = AudioCompressionManager.GetPcmFormat(1, 16, samplesPerSec);
    MemoryStream ms = new MemoryStream();
    BinaryReader br = new BinaryReader(File.OpenRead(voxFile));
    WaveWriter ww = new WaveWriter(ms, AudioCompressionManager.FormatBytes(format));
    Vox.Vox2Wav(br, ww);
    br.Close();
    WaveReader wr = new WaveReader(ms);
    byte[] data = wr.ReadData();
    wr.Close();
    ww.Close();
    IntPtr formatGsm = AudioCompressionManager.GetCompatibleFormat(format, AudioCompressionManager.Gsm610FormatTag);
    byte[] dataGsm = AudioCompressionManager.Convert(format, formatGsm, data, false);
    WaveWriter wwGsm = new WaveWriter(File.Create(wavFile), AudioCompressionManager.FormatBytes(formatGsm));
    wwGsm.WriteData(dataGsm);
    wwGsm.Close();
}


问:
SAPUI5: When I add custom columns to smart table they don't show in filter tab
I want to use smart table with a named model. If we use a named model then it does not show the data. One possibility is to use custom list and custom columns. But as soon as I use the custom List it shows data but it will remove the defined custom columns from the "Filter, Group and sort" tabs. It means in the P13N dialog you can just play with the position of columns (As soon as you define the custom columns for all fields it will remove the "Filter, Group and sort" tabs from the P13N dialog).

I need to use named model because of some reasons. Then I need to use custom list items and columns. Now the question is how I can keep these fields or columns in the filtering, sorting and grouping tabs in P13N dialog.

```<code><smartTable:SmartTable id="__smartTableMlst" entitySet="ProjectHeaderMstSet" tableBindingPath="TableMlstJsonModel>/ProjectHeaderMstSet"
header="{i18n>tableMlstTitle}" showRowCount="true" tableType="Responsive" showFullScreenButton="false" useVariantManagement="false"
enableAutoBinding="true" ignoredFields="ProjectDefinition,Method,Refnumber" useExportToExcel="false"
initiallyVisibleFields="MilestoneNumber,Description,OffsetMilestoneDate,OffsetMilestoneDateUnit">
<smartTable:customToolbar>
    <m:OverflowToolbar design="Transparent">
        <m:ToolbarSpacer/>
        <m:Button type="Transparent" press="onRefreshMlstBtnPress" icon="sap-icon://refresh" tooltip="{i18n>refreshBtnTooltip}"/>
        <m:Button type="Transparent" press="onAddMlstBtnPress" icon="sap-icon://add" tooltip="{i18n>createBtnTooltip}"
            enabled="{objectView>/tableMlstBtnAddEnabledFinal}"/>
        <m:Button type="Transparent" press="onDeleteMlstBtnPress" icon="sap-icon://delete" tooltip="{i18n>deleteBtnTooltip}"
            enabled="{objectView>/tableMlstBtnDelEnabledFinal}"/>
    </m:OverflowToolbar>
</smartTable:customToolbar>
<m:Table id="tableMlst" mode="MultiSelect" busy="{objectView>/tableMlstBusy}">
    <m:columns>
        <m:Column>
            <m:customData>
                <core:CustomData key="p13nData" value='\{"columnKey": "MilestoneNumber", "leadingProperty": "MilestoneNumber"}'/>
            </m:customData>
            <m:Text text="{/#ProjectHeaderMst/MilestoneNumber/@sap:label}"/>
        </m:Column>
    </m:columns>
    <m:items>
        <m:ColumnListItem type="Navigation" press="onPress">
            <m:cells>
                <m:Text text="{path: 'TableMlstJsonModel>MilestoneNumber', formatter: '.formatter.intNumber'}"/>
                <m:Text text="{TableMlstJsonModel>Description}"/>
                <m:Text text="{TableMlstJsonModel>OffsetMilestoneDate}"/>
                <m:Text text="{TableMlstJsonModel>OffsetMilestoneDateUnit}"/>
                <m:Text text="{TableMlstJsonModel>Activity}"/>
                <m:Text text="{TableMlstJsonModel>ActivityName}"/>
                <m:Text text="{TableMlstJsonModel>Aedat}"/>
                <m:Text text="{TableMlstJsonModel>Aenam}"/>
                <m:Text text="{TableMlstJsonModel>Erdat}"/>
                <m:Text text="{TableMlstJsonModel>Ernam}"/>
                <m:Text text="{TableMlstJsonModel>MlstSmlnr}"/>
                <m:Text text="{TableMlstJsonModel>Network}"/>
                <m:Text text="{TableMlstJsonModel>NetworkName}"/>
            </m:cells>
        </m:ColumnListItem>
    </m:items>
</m:Table>
</smartTable:SmartTable>
</code>```

I know about the usage of annotation files in smart tables, but is it possible to use annotation files with named JSON models? In the following image You can see how the MilestoneNumber has been removed from the filter list.

答:
You just need to pass filterProperty and sortProperty in custom column. You even can play with the starting position of the column or its visibility.

these are the key points of your answer

I added them for two columns of your code. Be aware by defining the columns, the property, initiallyVisibleFields will be ignored. Then you need to pass the visibility of the Column like this:

Here is modified code:

```<code>    <smartTable:SmartTable id="__smartTableMlst" entitySet="ProjectHeaderMstSet" tableBindingPath="TableMlstJsonModel>/ProjectHeaderMstSet"
header="{i18n>tableMlstTitle}" showRowCount="true" tableType="Responsive" showFullScreenButton="false" useVariantManagement="false"
enableAutoBinding="true" ignoredFields="ProjectDefinition,Method,Refnumber" useExportToExcel="false">
<smartTable:customToolbar>
<m:OverflowToolbar design="Transparent">
<m:ToolbarSpacer/>
<m:Button type="Transparent" press="onRefreshMlstBtnPress" icon="sap-icon://refresh" tooltip="{i18n>refreshBtnTooltip}"/>
<m:Button type="Transparent" press="onAddMlstBtnPress" icon="sap-icon://add" tooltip="{i18n>createBtnTooltip}"
enabled="{objectView>/tableMlstBtnAddEnabledFinal}"/>
<m:Button type="Transparent" press="onDeleteMlstBtnPress" icon="sap-icon://delete" tooltip="{i18n>deleteBtnTooltip}"
enabled="{objectView>/tableMlstBtnDelEnabledFinal}"/>
</m:OverflowToolbar>
</smartTable:customToolbar>
<m:Table id="tableMlst" mode="MultiSelect" busy="{objectView>/tableMlstBusy}">
<m:columns>
<m:Column visible="true">
<m:customData >
<core:CustomData key="p13nData" value='\{"sortProperty": "MilestoneNumber", "filterProperty": "MilestoneNumber", "columnKey": "MilestoneNumber", "leadingProperty": "MilestoneNumber", "columnIndex":"0"}'/>
</m:customData>
<m:Text text="{/#ProjectHeaderMst/MilestoneNumber/@sap:label}"/>
</m:Column>
<m:Column visible="false">
<m:customData>
<core:CustomData key="p13nData" value='\{"sortProperty": "Description", "filterProperty": "Description", "columnKey": "Description", "leadingProperty": "Description", "columnIndex":"1"}'/>
</m:customData>
<m:Text text="{/#ProjectHeaderMst/Description/@sap:label}"/>
</m:Column>
</m:columns>
<m:items>
<m:ColumnListItem type="Navigation" press="onPress">
<m:cells>
<m:Text text="{path: 'TableMlstJsonModel>MilestoneNumber', formatter: '.formatter.intNumber'}"/>
<m:Text text="{TableMlstJsonModel>Description}"/>
<m:Text text="{TableMlstJsonModel>OffsetMilestoneDate}"/>
<m:Text text="{TableMlstJsonModel>OffsetMilestoneDateUnit}"/>
<m:Text text="{TableMlstJsonModel>Activity}"/>
<m:Text text="{TableMlstJsonModel>ActivityName}"/>
<m:Text text="{TableMlstJsonModel>Aedat}"/>
<m:Text text="{TableMlstJsonModel>Aenam}"/>
<m:Text text="{TableMlstJsonModel>Erdat}"/>
<m:Text text="{TableMlstJsonModel>Ernam}"/>
<m:Text text="{TableMlstJsonModel>MlstSmlnr}"/>
<m:Text text="{TableMlstJsonModel>Network}"/>
<m:Text text="{TableMlstJsonModel>NetworkName}"/>
</m:cells>
</m:ColumnListItem>
</m:items>
</m:Table>
</smartTable:SmartTable>
</code>```

have fun

ContentLicense: CC BY-SA 3.0

Body:
I want to use smart table with a named model. If we use a named model then it does not show the data. One possibility is to use custom list and custom columns. But as soon as I use the custom List it shows data but it will remove the defined custom columns from the "Filter, Group and sort" tabs. It means in the P13N dialog you can just play with the position of columns (As soon as you define the custom columns for all fields it will remove the "Filter, Group and sort" tabs from the P13N dialog).

I need to use named model because of some reasons. Then I need to use custom list items and columns. Now the question is how I can keep these fields or columns in the filtering, sorting and grouping tabs in P13N dialog.

<smartTable:SmartTable id="__smartTableMlst" entitySet="ProjectHeaderMstSet" tableBindingPath="TableMlstJsonModel>/ProjectHeaderMstSet"
header="{i18n>tableMlstTitle}" showRowCount="true" tableType="Responsive" showFullScreenButton="false" useVariantManagement="false"
enableAutoBinding="true" ignoredFields="ProjectDefinition,Method,Refnumber" useExportToExcel="false"
initiallyVisibleFields="MilestoneNumber,Description,OffsetMilestoneDate,OffsetMilestoneDateUnit">
<smartTable:customToolbar>
    <m:OverflowToolbar design="Transparent">
        <m:ToolbarSpacer/>
        <m:Button type="Transparent" press="onRefreshMlstBtnPress" icon="sap-icon://refresh" tooltip="{i18n>refreshBtnTooltip}"/>
        <m:Button type="Transparent" press="onAddMlstBtnPress" icon="sap-icon://add" tooltip="{i18n>createBtnTooltip}"
            enabled="{objectView>/tableMlstBtnAddEnabledFinal}"/>
        <m:Button type="Transparent" press="onDeleteMlstBtnPress" icon="sap-icon://delete" tooltip="{i18n>deleteBtnTooltip}"
            enabled="{objectView>/tableMlstBtnDelEnabledFinal}"/>
    </m:OverflowToolbar>
</smartTable:customToolbar>
<m:Table id="tableMlst" mode="MultiSelect" busy="{objectView>/tableMlstBusy}">
    <m:columns>
        <m:Column>
            <m:customData>
                <core:CustomData key="p13nData" value='\{"columnKey": "MilestoneNumber", "leadingProperty": "MilestoneNumber"}'/>
            </m:customData>
            <m:Text text="{/#ProjectHeaderMst/MilestoneNumber/@sap:label}"/>
        </m:Column>
    </m:columns>
    <m:items>
        <m:ColumnListItem type="Navigation" press="onPress">
            <m:cells>
                <m:Text text="{path: 'TableMlstJsonModel>MilestoneNumber', formatter: '.formatter.intNumber'}"/>
                <m:Text text="{TableMlstJsonModel>Description}"/>
                <m:Text text="{TableMlstJsonModel>OffsetMilestoneDate}"/>
                <m:Text text="{TableMlstJsonModel>OffsetMilestoneDateUnit}"/>
                <m:Text text="{TableMlstJsonModel>Activity}"/>
                <m:Text text="{TableMlstJsonModel>ActivityName}"/>
                <m:Text text="{TableMlstJsonModel>Aedat}"/>
                <m:Text text="{TableMlstJsonModel>Aenam}"/>
                <m:Text text="{TableMlstJsonModel>Erdat}"/>
                <m:Text text="{TableMlstJsonModel>Ernam}"/>
                <m:Text text="{TableMlstJsonModel>MlstSmlnr}"/>
                <m:Text text="{TableMlstJsonModel>Network}"/>
                <m:Text text="{TableMlstJsonModel>NetworkName}"/>
            </m:cells>
        </m:ColumnListItem>
    </m:items>
</m:Table>
</smartTable:SmartTable>

I know about the usage of annotation files in smart tables, but is it possible to use annotation files with named JSON models? In the following image You can see how the MilestoneNumber has been removed from the filter list.

Body:
You just need to pass filterProperty and sortProperty in custom column. You even can play with the starting position of the column or its visibility.

these are the key points of your answer

I added them for two columns of your code. Be aware by defining the columns, the property, initiallyVisibleFields will be ignored. Then you need to pass the visibility of the Column like this:

Here is modified code:

    <smartTable:SmartTable id="__smartTableMlst" entitySet="ProjectHeaderMstSet" tableBindingPath="TableMlstJsonModel>/ProjectHeaderMstSet"
header="{i18n>tableMlstTitle}" showRowCount="true" tableType="Responsive" showFullScreenButton="false" useVariantManagement="false"
enableAutoBinding="true" ignoredFields="ProjectDefinition,Method,Refnumber" useExportToExcel="false">
<smartTable:customToolbar>
<m:OverflowToolbar design="Transparent">
<m:ToolbarSpacer/>
<m:Button type="Transparent" press="onRefreshMlstBtnPress" icon="sap-icon://refresh" tooltip="{i18n>refreshBtnTooltip}"/>
<m:Button type="Transparent" press="onAddMlstBtnPress" icon="sap-icon://add" tooltip="{i18n>createBtnTooltip}"
enabled="{objectView>/tableMlstBtnAddEnabledFinal}"/>
<m:Button type="Transparent" press="onDeleteMlstBtnPress" icon="sap-icon://delete" tooltip="{i18n>deleteBtnTooltip}"
enabled="{objectView>/tableMlstBtnDelEnabledFinal}"/>
</m:OverflowToolbar>
</smartTable:customToolbar>
<m:Table id="tableMlst" mode="MultiSelect" busy="{objectView>/tableMlstBusy}">
<m:columns>
<m:Column visible="true">
<m:customData >
<core:CustomData key="p13nData" value='\{"sortProperty": "MilestoneNumber", "filterProperty": "MilestoneNumber", "columnKey": "MilestoneNumber", "leadingProperty": "MilestoneNumber", "columnIndex":"0"}'/>
</m:customData>
<m:Text text="{/#ProjectHeaderMst/MilestoneNumber/@sap:label}"/>
</m:Column>
<m:Column visible="false">
<m:customData>
<core:CustomData key="p13nData" value='\{"sortProperty": "Description", "filterProperty": "Description", "columnKey": "Description", "leadingProperty": "Description", "columnIndex":"1"}'/>
</m:customData>
<m:Text text="{/#ProjectHeaderMst/Description/@sap:label}"/>
</m:Column>
</m:columns>
<m:items>
<m:ColumnListItem type="Navigation" press="onPress">
<m:cells>
<m:Text text="{path: 'TableMlstJsonModel>MilestoneNumber', formatter: '.formatter.intNumber'}"/>
<m:Text text="{TableMlstJsonModel>Description}"/>
<m:Text text="{TableMlstJsonModel>OffsetMilestoneDate}"/>
<m:Text text="{TableMlstJsonModel>OffsetMilestoneDateUnit}"/>
<m:Text text="{TableMlstJsonModel>Activity}"/>
<m:Text text="{TableMlstJsonModel>ActivityName}"/>
<m:Text text="{TableMlstJsonModel>Aedat}"/>
<m:Text text="{TableMlstJsonModel>Aenam}"/>
<m:Text text="{TableMlstJsonModel>Erdat}"/>
<m:Text text="{TableMlstJsonModel>Ernam}"/>
<m:Text text="{TableMlstJsonModel>MlstSmlnr}"/>
<m:Text text="{TableMlstJsonModel>Network}"/>
<m:Text text="{TableMlstJsonModel>NetworkName}"/>
</m:cells>
</m:ColumnListItem>
</m:items>
</m:Table>
</smartTable:SmartTable>

have fun


问:
Placing an imageview at the center of the layout regardless of screen size?
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

```<code><?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

答:
You have to try with android:layout_centerInParent="true"

```<code><?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:id="@+id/imageView"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_edit" />
</RelativeLayout>
</code>```

Body:
I am new to Android and so this is me experimenting with my layouts. I want to place an imageview at the center of the layout screen and it should be at the center regardless of device size or resolutions. Additionally, the imageview should automatically scale up in size depending on the device sizes. How should I go about it ?

This is what I tried so far.

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context="com.inducesmile.androidcameraapi2.AndroidCameraApi">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_alignEnd="@+id/btn_takepicture"
        android:layout_marginTop="140dp"
        android:src="@drawable/rectangle" />
</RelativeLayout>

Body:
You have to try with android:layout_centerInParent="true"

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical">
    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true"/>
    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="100dp"
        android:id="@+id/imageView"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_edit" />
</RelativeLayout>


问:
UICollectionView animate cell image when selected
I have a menu bar created with UICollectionView in my App. I want to do animation on a selected Cell. Now i am just changing the image on the selected cell by overriding isSelected in collectionViewCell class. How can i do a animation like in this image on bottom. Any helps will be appreciated.

Image of my menu bar:

答:
let's say you want to animate (eg: with a fading) the transition between two images, when you change the image (in your isSelected) you might use this code:

```<code>UIView.transition(with: self, duration: 0.25, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
// change the image
}
</code>```

Body:
let's say you want to animate (eg: with a fading) the transition between two images, when you change the image (in your isSelected) you might use this code:

UIView.transition(with: self, duration: 0.25, options: UIViewAnimationOptions.transitionCrossDissolve, animations: {
// change the image
}


问:
static list in Android Activity and memory leak
I have an ArrayList with more than 1000 string items in an Activity. Number of members of ArrayList does not change and no element update occurs. That Activity can be created and destroyed many times during application life time, but also it may be a few times. Also, ArrayList will be used to construct a ListView. Now I have two approaches in about ArrayList:

setting its variable as static to avoid creating objects and initializing ArrayList each time in onCreate() of Activity

creating and initializing ArrayList in onCreate() of Activity to avoid memory leak

I do not know which way is better or is there any other way?

答:
Unfortunatelly I can not honestly tell you, if there is any better way to solve your problem because you do not explain what for the mentioned Arraylist is used for. Try to explain us more about the Arraylist and we will see. If I should consider two ways you described, I have this notes:

Im not sure what do you mean in this point but if i see words like string and static to avoid im not sure if its helps because this optimlization is done by java it self

recreating fat objects can do some troubles to you.

At the end I recommend to you move the Arraylist outside of Activity, so it will be created only one. If Strings are different in each Activity, you still can create only as much mutations of sets as you need in whole app.


问:
In android geolocation not working in emulator and also in mobiles
In my application the location updates are not working and the app get closed when i click on start location updates button. I am a beginner i doesnt know how to debug this error.What i want from my application is

the application must updates the location on every minutes

the application will work on background and it will close when we close the applications like music player

Main_activity.class

```<code>package com.example.admin.locationapidemo;
import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.sql.Connection;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener{

 - List item

private static final String TAG = MainActivity.class.getSimpleName();
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;

    private boolean mRequestLocationUpdates = false;

    private LocationRequest mLocationRequest;

    private static int UPDATE_INTERVAL = 10000;
    private static int FATEST_INTERVAL = 5000;
    private static int DISPLACEMENT = 10;

    private TextView lblLocation;
    private Button btnShowLocation, btnStartLocationUpdates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lblLocation = (TextView) findViewById(R.id.lblLocation);
        btnShowLocation = (Button) findViewById(R.id.buttonShowLocation);
        btnStartLocationUpdates = (Button) findViewById(R.id.buttonLocationUpdates);

        if(checkPlayServices()) {
            buildGoogleApiClient();
            createLocationRequest();
        }

        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayLocation();
            }
        });

        btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePeriodLocationUpdates();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();
        if(mGoogleApiClient.isConnected() && mRequestLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if(mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    private void displayLocation() {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longtitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longtitude);
        } else {
            lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
        }
    }

    private void togglePeriodLocationUpdates() {
        if(!mRequestLocationUpdates) {
            btnStartLocationUpdates.setText(getString(R.string.btn_stop_location_updates));

            mRequestLocationUpdates = true;

            startLocationUpdates();
        } else {
            btnStartLocationUpdates.setText(getString(R.string.btn_start_location_updates));

            mRequestLocationUpdates = false;

            stopLocationUpdates();
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(resultCode != ConnectionResult.SUCCESS) {
            if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        displayLocation();

        if(mRequestLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show();

        displayLocation();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed: " + connectionResult.getErrorCode());
    }
}
</code>```

My xml file:

```<code><?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-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:background="@color/view_bg">

    <TextView
        android:text="@string/lbl_you_are_at"
        android:layout_marginTop="25dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="25dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/lblLocation"
        android:padding="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="16dp" />

    <Button
        android:id="@+id/buttonShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_get_location"
        android:textColor="@color/view_bg"/>

    <Button
        android:id="@+id/buttonLocationUpdates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_start_location_updates"
        android:textColor="@color/view_bg"/>

</LinearLayout>
</code>```

Manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admin.locationapidemo">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>
</code>```

答:
```<code>private void displayLocation() {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longtitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longtitude);
        } else {
            lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
        }
    }
</code>```

remove this line

```<code>mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
</code>```

because in onLocationChanged() you are assigning value to mLastLocation, so try to use that assigned value.

Body:
In my application the location updates are not working and the app get closed when i click on start location updates button. I am a beginner i doesnt know how to debug this error.What i want from my application is

the application must updates the location on every minutes

the application will work on background and it will close when we close the applications like music player

Main_activity.class

package com.example.admin.locationapidemo;
import android.app.Activity;
import android.location.Location;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import java.sql.Connection;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener{

 - List item

private static final String TAG = MainActivity.class.getSimpleName();
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;
    private GoogleApiClient mGoogleApiClient;

    private boolean mRequestLocationUpdates = false;

    private LocationRequest mLocationRequest;

    private static int UPDATE_INTERVAL = 10000;
    private static int FATEST_INTERVAL = 5000;
    private static int DISPLACEMENT = 10;

    private TextView lblLocation;
    private Button btnShowLocation, btnStartLocationUpdates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lblLocation = (TextView) findViewById(R.id.lblLocation);
        btnShowLocation = (Button) findViewById(R.id.buttonShowLocation);
        btnStartLocationUpdates = (Button) findViewById(R.id.buttonLocationUpdates);

        if(checkPlayServices()) {
            buildGoogleApiClient();
            createLocationRequest();
        }

        btnShowLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displayLocation();
            }
        });

        btnStartLocationUpdates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                togglePeriodLocationUpdates();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        checkPlayServices();
        if(mGoogleApiClient.isConnected() && mRequestLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        if(mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    private void displayLocation() {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longtitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longtitude);
        } else {
            lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
        }
    }

    private void togglePeriodLocationUpdates() {
        if(!mRequestLocationUpdates) {
            btnStartLocationUpdates.setText(getString(R.string.btn_stop_location_updates));

            mRequestLocationUpdates = true;

            startLocationUpdates();
        } else {
            btnStartLocationUpdates.setText(getString(R.string.btn_start_location_updates));

            mRequestLocationUpdates = false;

            stopLocationUpdates();
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(resultCode != ConnectionResult.SUCCESS) {
            if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG)
                        .show();
                finish();
            }
            return false;
        }
        return true;
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        displayLocation();

        if(mRequestLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show();

        displayLocation();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(TAG, "Connection failed: " + connectionResult.getErrorCode());
    }
}

My xml file:

<?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-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:background="@color/view_bg">

    <TextView
        android:text="@string/lbl_you_are_at"
        android:layout_marginTop="25dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="25dp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/lblLocation"
        android:padding="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:textSize="16dp" />

    <Button
        android:id="@+id/buttonShowLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_get_location"
        android:textColor="@color/view_bg"/>

    <Button
        android:id="@+id/buttonLocationUpdates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:background="@color/btn_bg"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:text="@string/btn_start_location_updates"
        android:textColor="@color/view_bg"/>

</LinearLayout>

Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admin.locationapidemo">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

Body:
private void displayLocation() {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longtitude = mLastLocation.getLongitude();

            lblLocation.setText(latitude + ", " + longtitude);
        } else {
            lblLocation.setText("Couldn't get the location. Make sure location is enabled on the device");
        }
    }

remove this line

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

because in onLocationChanged() you are assigning value to mLastLocation, so try to use that assigned value.


问:
Misalignment of Facebook & Twitter buttons
The page contains two buttons, from twitter and from facebook.

What I'm observing in Firefox 3.5.15 is:

While the page is loading, the buttons are more or less aligned (I mean their bottom sides)

When the page is loaded, the facebook button moves a few pixels down, so that it's bottom side is lower than the bottom side of the twitter button.

If I reload the page, the buttons are again aligned, and remain in this state even after the page is loaded.

Can someone please explain what's going on and how to fix it?

答:
You can easily solve this issue with CSS:

iframe { float: left; padding-right: 10px; }

EIDT: If you want them to be centered, simply wrap them in a div (which they already are wrapped with, give that div a class or an ID. For example, let's give it a class of twfb for twitter/facebook. Now in the CSS we'll declare a width and automatic margins as so:

.twfb { width: 120px; margin: 0 auto; }

EDIT 2: To remove the large margin from the facebook, simply add this to your CSS:

.fb_edge_widget_with_comment { margin-left: -26ppx; }

That should align them nice and close to each other.

That should do it!

Good luck

ContentLicense: CC BY-SA 2.5


答:
Add android:layout_centerInParent="true" and android:gravity="center_vertical"

Remove android:layout_alignEnd="@+id/btn_takepicture"//as this will align imageview to end

```<code><?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">

    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="140dp"
        android:layout_centerInParent="true"
        android:gravity="center_vertical"
        android:src="@drawable/rectangle" />
</RelativeLayout>
</code>```

Title: Placing an imageview at the center of the layout regardless of screen size?

Body:
Add android:layout_centerInParent="true" and android:gravity="center_vertical"

Remove android:layout_alignEnd="@+id/btn_takepicture"//as this will align imageview to end

<?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">

    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btn_takepicture"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/btn_takepicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="16dp"
        android:text="take_picture" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="140dp"
        android:layout_centerInParent="true"
        android:gravity="center_vertical"
        android:src="@drawable/rectangle" />
</RelativeLayout>


问:
uitableviewcell not showing swift 3
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

```<code>class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`
</code>```

my function is

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`
</code>```

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

答:
Remove code

```<code>self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")
</code>```

Write below code in cartTableViewCell

```<code>override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            // code common to all your cells goes here
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
</code>```

Now modify your code with below code

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell
    if cell == nil {
            cell = cartTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }
    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}
</code>```

Title: uitableviewcell not showing swift 3

Body:
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`

my function is

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

Body:
Remove code

self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell")

Write below code in cartTableViewCell

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            // code common to all your cells goes here
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }

Now modify your code with below code

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell
    if cell == nil {
            cell = cartTableViewCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }
    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}