I need to place my app icon on the left side of the toolbar, so I placed an ImageButton in Toolbar.axml. I set the SetContentView so that I can access the ImageButton using FindViewById and Listen to the click event.
But After adding the SetContentView line my app throws UnhandledException.
Below is my Main.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
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">
<ImageButton
android:src="#drawable/appicon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:id="#+id/homeicon" />
</android.support.v7.widget.Toolbar>
</LinearLayout>
And my MainActivity.cs is like below:
[Activity(Label = "XamarinToolBar", Icon = "#drawable/icon", Theme =
"#style/MainTheme", MainLauncher = true, ConfigurationChanges =
ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity :
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
//TabLayoutResource = Resource.Layout.Tabbar;
//ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
ImageButton homeButton = (ImageButton)FindViewById<ImageButton>(Resource.Id.homeicon);
homeButton.Click += HomeButton_Click;
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
private void HomeButton_Click(object sender, EventArgs e)
{
}
}
The Problem is here :
public class MainActivity :
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
You are mixing up the xamarin forms FormsAppCompatActivity with your AppCompactActivity and remove these two lines from your cs file
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
I hope it helps
Goodluck!
i think you are trying to mix and match the xamarin.forms "FormsAppCompatActivity" and make it behave like a normal android Activity in which shouldn't be the case because xamarin.forms "FormsAppCompatActivity" has its own underlying rendering engine through the use of xaml pages (e.g. ContentPage, MasterDetailPage etc.). Try to create an Android project instead.
Related
I am trying to build a functional BottomAppBar in Android Java.
All it seems to work except that I don´t know how to put a listener in the items of bottomMenu.
The Material.io documentation is incomplete in this part.
follow my code:
public class MainActivity extends AppCompatActivity {
private BottomAppBar bottomAppBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.setNavigationOnClickListener(new *OnClickListener()* {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "TEste da bottom bar", Toast.LENGTH_SHORT).show();
}
});
bottomAppBar.setOnMenuItemClickListener(new *OnMenuItemClickListener()* {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.item_relatorio:
Toast.makeText(getApplicationContext(),"Item relatorio",Toast.LENGTH_LONG).show();
break;
case R.id.item_sobre:
Toast.makeText(getApplicationContext(),"Item sobre",Toast.LENGTH_LONG).show();
break;
case R.id.item_sair:
Toast.makeText(getApplicationContext(),"Item sair",Toast.LENGTH_LONG).show();
break;
}
return false;
}
});
This is my activity_main.XML
<?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="match_parent"
android:background="#drawable/greengrasstexture"
tools:context=".MainActivity">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:fabCradleMargin="10dp"
app:fabCradleRoundedCornerRadius="10dp"
app:fabCradleVerticalOffset="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="BottomAppBar">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation"
android:layout_marginRight="0dp"
app:menu="#menu/menu_bottom"
android:background="#color/white"/>
</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
follow my menu_bottom
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/item_CadLogin"
android:icon="#drawable/ic_login_24"
android:orderInCategory="100"
android:title="cadastro/login"
app:showAsAction="always"
/>
<item
android:id="#+id/item_preferencias"
android:icon="#drawable/ic_baseline_construction_24"
android:orderInCategory="200"
android:title="preferências"
app:showAsAction="always"
/>
<item
android:id="#+id/item_conta"
android:icon="#drawable/ic_baseline_account_circle_24"
android:orderInCategory="300"
android:title="Conta"
app:showAsAction="always"
/>
</menu>
Finally, from Material.io docs, the incomplete code:
(in kotlin i presume, but i need it in java)
bottomAppBar.setNavigationOnClickListener {
// Handle navigation icon press
}
bottomAppBar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.search -> {
// Handle search icon press
true
}
R.id.more -> {
// Handle more item (inside overflow menu) press
true
All the tutorials, stops focused just on how to build th BottomAppBar but not in how to implements click functionality to the menu icons.
Thanks in advance for any help.
Is it possible to implement app:tabMode="scrollable" in specific page only? I have 2 page that contains TabBar and the other one should be in fixed mode only.
I created a custom TabBar and in Android and it is deployed on all my TabBar page.
My customTabBar.axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="80dp"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="#FF3300"
app:tabTextAppearance="#style/CustomTab"
app:tabMode="scrollable" />
And for my MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
AppCompatDelegate.DefaultNightMode = AppCompatDelegate.ModeNightNo;
TabLayoutResource = Resource.Layout.CustomTabbar;
LoadApplication(new App());
}
I have created a custom view that uses data binding. It works fine in the application but it throws an error in the Android studio IDE.
DataBindingUtil.inflate throws an error because some of the fields in the binding are null in edit mode.
I can get around this by using isInEditMode and using normal inflate when it edit mode. However, that means that the preview is never accurate because no data is bound to the fields. If I try to skirt around data binding in edit mode and then poke in values directly then "why use data binding at all"?
Is there a way to use data binding in a custom view and get an accurate preview in the IDE?
public class HelpItem extends LinearLayoutCompat {
private String mText = "Dog";
private Drawable mDrawable;
public HelpItem(Context context) {
super(context);
init(context, null, 0);
}
public HelpItem(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
public HelpItem(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr);
}
private void getStyleableAttributes(Context context, AttributeSet attrs) {
if (null != attrs) {
TypedArray attributes = context.obtainStyledAttributes(attrs,
R.styleable.HelpItem);
mDrawable = attributes.getDrawable(R.styleable.HelpItem_helpItemIcon);
mText = attributes.getString(R.styleable.HelpItem_helpItemText);
attributes.recycle();
}
}
private void init(Context context, AttributeSet attrs, #SuppressWarnings("unused") int defStyle) {
getStyleableAttributes(context, attrs);
LayoutInflater factory = LayoutInflater.from(context);
// if (isInEditMode())
// inflate(context, R.layout.view_help_item, this);
// else {
ViewHelpItemBinding binding = DataBindingUtil.inflate(factory, R.layout.view_help_item, this, true);
binding.setText(mText);
binding.setIcon(mDrawable);
ImageView iv = binding.getRoot().findViewById(R.id.help_icon);
if (null != iv) iv.setImageDrawable(mDrawable);
// }
}
}
Here is my custom view layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<data>
<variable
name="icon"
type="android.graphics.drawable.Drawable" />
<variable
name="text"
type="String" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="12dp"
>
<ImageView
android:id="#+id/help_icon"
android:layout_width="70dp"
android:layout_height="24dp"
android:layout_gravity="center_vertical"
app:icon="#{icon}"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
style="#style/ContactTextBold"
android:text="#{text}"
tools:text="#string/title_help_getting_started"
android:textColor="#color/textColor"
android:textSize="20sp"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="24dp"
android:layout_gravity="center_vertical"
android:layout_marginRight="20dp"
app:srcCompat="#drawable/ic_baseline_keyboard_arrow_right_24px"
/>
</LinearLayout>
<include layout="#layout/seperator_view_gray" />
</LinearLayout>
</layout>
Here is an example of how I include the custom view in a layout
<com.apcon.intellaviewmobile.view.HelpItem
android:id="#+id/getting_started"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:helpItemIcon="#drawable/ic_arrow_right"
app:helpItemText="#string/title_help_getting_started"
/>
Here is the error being thrown in the IDE
java.lang.NullPointerException
at com.apcon.intellaviewmobile.databinding.ViewHelpItemBindingImpl.<init>(ViewHelpItemBindingImpl.java:35)
at com.apcon.intellaviewmobile.databinding.ViewHelpItemBindingImpl.<init>(ViewHelpItemBindingImpl.java:29)
at com.apcon.intellaviewmobile.DataBinderMapperImpl.getDataBinder(DataBinderMapperImpl.java:118)
at androidx.databinding.MergedDataBinderMapper.getDataBinder(MergedDataBinderMapper.java:74)
at androidx.databinding.DataBindingUtil.bind(DataBindingUtil.java:199)
at androidx.databinding.DataBindingUtil.bindToAddedViews(DataBindingUtil.java:327)
at androidx.databinding.DataBindingUtil.inflate(DataBindingUtil.java:128)
at androidx.databinding.DataBindingUtil.inflate(DataBindingUtil.java:95)
at com.apcon.intellaviewmobile.view.HelpItem.init(HelpItem.java:51)
at com.apcon.intellaviewmobile.view.HelpItem.<init>(HelpItem.java:27)
at sun.reflect.GeneratedConstructorAccessor1708.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:403)
at org.jetbrains.android.uipreview.ViewLoader.loadClass(ViewLoader.java:186)
at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:144)
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.loadView(LayoutlibCallbackImpl.java:309)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:418)
at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:429)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:333)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:863)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:866)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:837)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:394)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:326)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:391)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:195)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:540)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$5(RenderTask.java:666)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Actual results: The IDE throws an error when previewing
Desired results: To be able to use data binding in a custom view and see WYSIWIG preview in Android Studio.
Android Studio Chipmunk doesnt have problem.
Android Studio Dolphin and Electric Eel have this CustomView databinding preview problem
According to this https://issuetracker.google.com/issues/260134720, Android Flamingo also doesnt have has problem, but it's still in beta
Im currently downgrade this Chipmunk version and it's working well
Android Studio Chipmunk | 2021.2.1 May 9, 2022
You can download archive from here https://developer.android.com/studio/archive
I have a very simple Xamarin Android app. It has a text box and a button. Here's the activity_main.axml file in Resources.Layout:
<?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">
<TextView
android:text="0"
android:textSize="50sp"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtNumber"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp" />
<Button
android:text="Get Number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btnAutoGenerate" />
In the Solution Explorer I have Assets and Resources.
Under Resources is layout and under layout is activity_main.axml
Not complex at all.
In MainActivity.cs, the OnCreate procedure is this:
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TextView txtNumber;
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
txtkNumber = FindViewById<TextView>(Resource.Id.txtNumber);
FindViewById<Button>(Resource.Id.btnAutoGenerate).Click += (o, e) =>
txtNumber.Text = btnAutoGenerate_Click(o, e);
}
I'm not sure where Resource is defined (as in the xml it's Resources) but even though at first this compiled with no problem now I get the error: the name "Resource" does not exist in the current context.
Because when the default files are first generated, it is
SetContentView(Resource.Layout.activity_main);
even though the "Resource.Layout" is pointing to Resources.layout. Not sure why.
I am using VS2015 with Xamarin to create a multi-platform project that can show a splashscreen and then load a webpage in a webview. Here is my project structure. I am using a PCL project type as below:
TheApp (Portable)
-WebPageHoster.Xaml //Contains a WebView control
-WebPageHoster.Xaml.cs //sets the WebView controls source property to load a webpage
-App.Xaml
-App.Xaml.cs
TheApp.Droid
/Resources/drawable/splashlogo.png
/Resources/drawable/icon3.png
/Resources/values/Styles.xml
-MainActivity.cs
-SplashActivity.cs
TheApp.iOS
TheApp.WindowsPhone(Windows Phone 8.1)
This is the code in the Styles.xml
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<style name="Theme.Splash" parent="android:Theme">
<item name="android:windowBackground">#drawable/splashlogo</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
SplashActivity.cs
[Activity(MainLauncher = true, NoHistory = true, Theme = "#style/Theme.Splash", Icon = "#drawable/icon3")]
public class SplashActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
Finish();
}
}
MainActivity.cs
[Activity(Label = "Splash App", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App()); // << Problem here
}
The LoadApplication method call in the OnCreate method above loads the app constructor of the App.Xaml.cs class which runs the following code
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new WebPageHoster() { Title = "Load Web-Page" });
}
This shows the splash screen and after setting the WebView's url reaches back to the OnCreate method and gives this error
System.NullReferenceException: Object reference not set to an instance of an object
I am unable to find what is causing this error. Here is the Android Manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="TheApp.TheApp" android:installLocation="auto" android:versionCode="1">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<application android:icon="#drawable/icon3" android:theme="#style/Theme.AppCompat" android:label="Splash Web Host"></application>
</manifest>
I tested your source code and your MainActivity derives from FormsAppCompatActivity.
In that case you must provide a theme that uses AppCompat.
To solve that, I added an AppCompat Theme to your styles:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="windowActionModeOverlay">true</item>
</style>
And then used it on your MainActivity:
[Activity(Label = "Southern Travel", Theme = "#style/AppTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity