I'm new to Android & was trying out the Bluetooth APIs of Google. Whenever I run my app on my phone, it crashes for some reason. I'm following the Google Developer's tutorial for the APIs & have made changes to my MainActivity.java & content.xml accordingly, but no use. Please have a look.
Here's my MainActivity.java
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.bluetooth.*;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn;
private BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void bluetoothDiscovery()
{
if(BA == null)
{
System.out.println("System Doesn't Support Bluetooth");
}
if(!BA.isEnabled())
{
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBTIntent,REQUEST_ENABLE_BT);
Toast.makeText(MainActivity.this,"Turned On!!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "ALREADY ON", Toast.LENGTH_LONG).show();
}
}
}
Here's my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluetoothapptry">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!-- <android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"
android:onClick="bluetoothDiscovery"/> -->
</android.support.design.widget.CoordinatorLayout>
Here's my content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluetoothapptry.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BTButton"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="bluetoothDiscovery"/>
</RelativeLayout>
And here's my logcat
03-13 02:06:34.719 18759-18759/vertex2016.mvjce.edu.bluetoothapptry E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluetoothapptry, PID: 18759
java.lang.IllegalStateException: Could not find method bluetoothDiscovery(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4789)
at android.view.View$PerformClick.run(View.java:19881)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Thank you for your time
Your method bluetoothDiscovery must accept a parameter of type View, see View.onClick for reference.
public void bluetoothDiscovery(View v) {}
When this method is called, v will be the View object that was clicked.
i.e.
switch ( v.getId() ) {
case R.id.button:
// do something
break;
case R.id.other_button
// do something else
break;
}
Where r.id.button comes from your definition in XML,
android:id="#+id/button"
It is using this, you could have a single onClick method that is called by multiple buttons, each one with their own action.
You need a View parameter in your onClick method
public void bluetoothDiscovery(View v)
Personally, I try not to add onClick in the XML because they are hard to find as you add more classes and layouts. You can just set the OnClickListener from the Java code for clearer visibility.
Related
I have followed the material guideline here but for some reason, the bottom navigation is not working for me. My app simply displays a white frame where the bottom navigation should be. What am I doing wrong? Please note that I commented out the onCreateOptionsMenu in my MainActivity.java shown below. If I uncomment this code, the items in my menu_bottom_navigation.xml show up in the app bar menu but I want to have them show up in the bottom navigation bar.
Build.gradle
...
implementation 'com.google.android.material:material:1.1.0'
...
Menu resource:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/discover"
android:enabled="true"
android:title="#string/title_activity_discover_movies"
android:icon="#drawable/ic_search_24px"/>
<item
android:id="#+id/favorites"
android:enabled="true"
android:title="#string/title_activity_favorite_movies"
android:icon="#drawable/ic_favorite_24px" />
</menu>
Layout resource:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".features.movieoptions.movielist.MainActivity">
<include
layout="#layout/toolbar_discover_movies"
android:id="#+id/toolbar_movie_list" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom"
android:background="#color/colorPrimary"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#color/colorTextIcons"
app:menu="#menu/menu_bottom_navigation"/>
</FrameLayout>
</LinearLayout>
MainActivity.java
package edu.bu.metcs.activitylifecycle.features.movieoptions.movielist;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import edu.bu.metcs.activitylifecycle.R;
import edu.bu.metcs.activitylifecycle.features.movieoptions.movielist.discover.DiscoverFragment;
import edu.bu.metcs.activitylifecycle.features.movieoptions.movielist.favorites.FavoritesFragment;
import edu.bu.metcs.activitylifecycle.shared.FragmentUtility;
/**********************************************************************************************************************
* This activity manages the apps fragments and decides which fragment should be displayed to the user.
*
* #author mlewis
* #version June 5, 2020
*********************************************************************************************************************/
public class MainActivity extends AppCompatActivity {
// Invariant of the MovieListActivity.java class
// 1. A shareActionProvider sends an implicit intent to apps capable of handling the text/plain MIME type.
// 2. The TAG is used by the Logcat for informational purposes.
private DiscoverFragment discoverFragment;
private FavoritesFragment favoritesFragment;
private static final String TAG = MainActivity.class.getSimpleName();
/**
* protected void onCreate(Bundle savedInstanceState)
* Performs initial Activity set up.
*
* #param savedInstanceState A bundle for any saved state from prior sessions that were destroyed.
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
discoverFragment = DiscoverFragment.newInstance();
favoritesFragment = FavoritesFragment.newInstance();
// Show discover fragment by default
setUpFragment(discoverFragment);
}
setUpBottomNavigation();
setUpToolbar();
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.menu_bottom_navigation, menu);
// return true;
// }
private void setUpFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentUtility.fragmentTransaction(fragmentManager, R.id.fragment_container, fragment);
}
private void setUpBottomNavigation() {
Log.d(TAG, "Setting bottom nav.");
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.discover:
Log.d(TAG, "discover was clicked.");
setUpFragment(discoverFragment);
return true;
case R.id.favorites:
Log.d(TAG, "favorites was clicked.");
setUpFragment(favoritesFragment);
return true;
}
return false;
}
});
}
private void setUpToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar_movie_list);
setSupportActionBar(toolbar);
}
}
Please see the white section at the bottom of the screen to see the issue:
As i Checked your layout. i found the mistake
1. Fragment Container(Frame layout) having wrong margin bottom
2. Need to add wight for fragment container(Frame Layout)
Corrected code as below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".features.movieoptions.movielist.MainActivity">
<include
layout="#layout/toolbar_discover_movies"
android:id="#+id/toolbar_movie_list" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#color/colorTextIcons"
app:menu="#menu/menu_bottom_navigation"/>
</FrameLayout>
</FrameLayout>
</LinearLayout>
None of the components I add on layout .xml are detected on the .java code.
I'm an absolute beginner trying to follow this tutorial: https://www.androidauthority.com/lets-build-a-simple-text-editor-for-android-773774/
So, this must be something really stupid haha
I've tried: restarting android studio, cleaning the project, rebuilding the project, invalidating caches, re-importing the project, deleting the .iml file and the .idea folder.
My code... it must be pretty much the same as in the tutorial except for the variable name, but here it goes:
MainActivity.java
package com.example.notezinhas;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
String ff = some_textView;
}
^ This last line is where the Cannot resolve symbol 'some_textView' shows up
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/some_textView"
layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/some_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
the logcat!
2019-04-03 23:52:33.075 9866-9992/? E/TransactionsProtoFiller: Client token done future failed
java.util.concurrent.ExecutionException: java.lang.Throwable: Account is null
at com.google.common.r.a.d.b(SourceFile:107)
at com.google.common.r.a.d.get(SourceFile:81)
at com.google.common.r.a.da.a(SourceFile:1)
at com.google.common.r.a.bf.a(SourceFile:28)
at com.google.android.apps.gsa.search.core.google.e.a.b(SourceFile:18)
at com.google.android.apps.gsa.search.core.google.e.a.a(SourceFile:8)
at com.google.android.apps.gsa.staticplugins.h.a.a(SourceFile:81)
at com.google.android.apps.gsa.staticplugins.h.b.c.a(Unknown Source:8)
at com.google.android.libraries.gsa.n.a.d.a(Unknown Source:2)
at com.google.common.r.a.cx.b(SourceFile:9)
at com.google.common.r.a.bs.run(SourceFile:5)
at com.google.common.r.a.cw.run(SourceFile:7)
at com.google.android.apps.gsa.shared.util.c.b.g.run(Unknown Source:3)
at com.google.android.apps.gsa.shared.util.c.b.be.run(SourceFile:3)
at com.google.android.apps.gsa.shared.util.c.b.be.run(SourceFile:3)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:914)
at com.google.android.apps.gsa.shared.util.c.b.l.run(SourceFile:6)
Caused by: java.lang.Throwable: Account is null
at com.google.android.apps.gsa.staticplugins.fl.d.a(SourceFile:6)
at com.google.android.apps.gsa.search.core.google.e.a.b(SourceFile:16)
at com.google.android.apps.gsa.search.core.google.e.a.a(SourceFile:8)
at com.google.android.apps.gsa.staticplugins.h.a.a(SourceFile:81)
at com.google.android.apps.gsa.staticplugins.h.b.c.a(Unknown Source:8)
at com.google.android.libraries.gsa.n.a.d.a(Unknown Source:2)
at com.google.common.r.a.cx.b(SourceFile:9)
at com.google.common.r.a.bs.run(SourceFile:5)
at com.google.common.r.a.cw.run(SourceFile:7)
at com.google.android.apps.gsa.shared.util.c.b.g.run(Unknown Source:3)
at com.google.android.apps.gsa.shared.util.c.b.be.run(SourceFile:3)
at com.google.android.apps.gsa.shared.util.c.b.be.run(SourceFile:3)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:914)
at com.google.android.apps.gsa.shared.util.c.b.l.run(SourceFile:6)
Have you seen this problem before? What should I do?
-_- To anyone who might see this:
Make sure you only access the components after setContentView(R.layout.activity_main); (in this case, I was trying to get it outside of the methods in the mainActivity class)
Get the right type of variable (I was trying to use the String type for a TextView)
Other things I did to get it working:
Get graddle off offline mode
Run a random git project, which installed a bunch of stuff I probably don't need. This was to make sure my Android Studio wasn't crazy, haha! But it could've been a factor on getting it running
So I want to implement a Bottom Sheet behavior and everything works fine except at first (when activity is created) the bottom sheet is not positioned how I configured it.
I can't find any information on why this is happening or if it is some configuration I am missing.
I prepared a sample code and some images to show the problem:
The activity (I haven't done anything, this is the initial template)
package com.example.testbottomsheet;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.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:fitsSystemWindows="true"
tools:context="com.example.flavio.testbottomsheet.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
<LinearLayout
android:id="#+id/transaction_history"
android:layout_width="match_parent"
android:layout_height="500dp"
android:background="#android:color/holo_orange_dark"
android:orientation="vertical"
app:behavior_hideable="false"
app:behavior_peekHeight="40dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<ImageView
android:id="#+id/bottomSheetHandler"
android:layout_width="match_parent"
android:layout_height="40dp"
android:contentDescription="Handles for bottom sheet"
android:src="#drawable/ic_expand_less_24dp" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#156de8"></FrameLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
As one can see I have a peekHeight of 40dp, and it works fine after I expand and close it )or just a small flick on top of the bottom sheet), however it is not initially set like this. I colored everything to be easier to spot:
Open Pane
Should-be initial state
IS initial state
From what I could see the bottom sheet is being placed 20dp bellow of the desired number configured in the XML.
Its a bug in design support lib.. take a look at this link:
https://code.google.com/p/android/issues/detail?id=203057
Try adding android:fitsSystemWindows="true" to the LinearLayout that you have added the BottomSheetBehaviour to.
I am having problems with ListView. It doesn't display. I know it's a common problem but I'm new to Android. In most examples, the problem is solved with layout_bellow property but I do not have any other controls.
Here is my XML code:
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gkmicro.trrrrrrrrrrrrrr.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/myListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
And here is my MainActivity.java:
package com.gkmicro.trrrrrrrrrrrrrr;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As your ListView is android:layout_alignParentBottom="true" it stick to bottom with android:layout_height="wrap_content"
So make ListView like this
<ListView
android:id="#+id/myListView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
Change your ListView to use all width and height of your parent RelativeLayout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.gkmicro.trrrrrrrrrrrrrr.MainActivity"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
By the way as recommended #Erik Jhordan Rey Caffrey use RecyclerView
EDIT: If you have any issues here is a good sample to implement a simple listView inside a RelativeLayout
Hope this helps!
I am new to the Android development world and I've built a simple "Hello World" app. First, activity requests a text. When the "Go" button is clicked, the app launches the second activity displaying the input text.
If I click the HOME button and then click the application icon, the app launches the first activity again but if I press-hold the home button and click the icon from the "Recent apps" bar, it resumes the app where I left.
How do I avoid this?
I need my app to resume even if the launcher icon is clicked.
MainActivity.java,
package com.example.myfirstandroidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view){
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.txtName);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayActivity.java,
package com.example.myfirstandroidapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class DisplayMessageActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, menu);
return true;
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
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" >
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtName"
android:layout_alignParentRight="true"
android:onClick="sendMessage"
android:text="Go!" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:text="Please input your name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
activity_display_message.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=".DisplayMessageActivity" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
AndroidManifest.xml,
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstandroidapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstandroidapp.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>
<activity
android:name="com.example.myfirstandroidapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstandroidapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstandroidapp.MainActivity" />
</activity>
</application>
</manifest>
Problem:
I'm not qualified to say this a bug, but there is a behaviour with release builds when starting the application from the launcher. It seems that instead of resuming the previous Activity, it adds a new Activity on top. There is a related bug report on this topic here.
Solution:
I'm working around this this by closing the Launcher Activity if it's not the root of the task, as a result the previous Activity in that task will be resumed.
if (!isTaskRoot()) {
finish();
return;
}
Issue for me was whenever app in installed by an apk with the click on 'Open' option it used to relaunch every time when we minimize it.
resolved it by
SplashActivity.java:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!isTaskRoot
&& intent.hasCategory(Intent.CATEGORY_LAUNCHER)
&& intent.action != null
&& intent.action.equals(Intent.ACTION_MAIN)) {
finish()
return
}
}