How to create a drop-down list in Android Studio? - android

I am trying to create a drop-down list for an activity in Android Studio. I have tried using the Spinner.
Here is my xml code:
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
Here is my Java code:
Spinner dropdown = findViewById(R.id.spinner1);
String[] items = new String[]{"1", "2", "3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
This is a screenshot of what it looks like:
As you can see, the drop-down list appears as a pop-up, however, I want the drop-down list to appear in a different way. See the image below as an example of what I want:
Does anyone have any ideas on how I could do this?

Actually it does look like there is a way with the Material design library called ExposedDropdownMenu
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/menu"
style="#style/Widget.MaterialComponents.TextInputLayout.FilledBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/label">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
/>
</com.google.android.material.textfield.TextInputLayout>
Obviously this is with TextInput and not a spinner so there will still be some custom logic to prevent typing if you dont want that
I personally have not tried it myself but it looks like what you want

Some ideas:
As #tyczj said, that is android's default layout that is showing, so there are some alternatives:
Create tour own custom layout
Use an external library like SearchableSpinner, it incorporates the search function and the item layout is similar from what you want.

Here I have found a useful example for a ComboBox/Spinner on Android:
https://abhiandroid.com/ui/spinner
Here is the code:
https://github.com/abhisheksaini4/SpinnerExamples/blob/master/SpinnerExamples.7z
The main codes include MainActivity.java:
package example.abhiandriod.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#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);
}
}
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">
<Spinner
android:id="#+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
menu_main.xml:
<menu 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" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
And AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.abhiandriod.spinnerexample" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

Modifying Android Search for ListView

I'm new to android app development and currently trying to figure out how to add search to an app. I did some searching and the tutorial that was the simplest for me to understand is here.
The app runs and searches as it should. The only issue is that the tutorial is for searching a ListView. The activity that my app's search is hosted in has other details(itemview, textview) that need to be on the screen so a ListView won't work for what I'm trying to do. How do I modify this example to provide a dropdown of suggestions as the user types into the search box? Ideally, I would like a search as seen in this image here.
ItemSearch.java
import android.app.SearchManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class ItemSearch extends AppCompatActivity {
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.item_search_activity);
final String[] months = {"January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"};
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, months);
final ListView listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = (String) listview.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
item_search_acitivity.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<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:id="#+id/item_view_activity"
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="com.example.me.ItemSearch">
<ImageView
/>
<ImageView
/>
<ImageView
/>
<TextView
/>
<TextView
/>
<TextView
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</ScrollView>
menu_search.xml under res/menu/menu_search
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/search"
android:title="#string/hint_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
searchable.xml under res/xml/searchable
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search_hint"
android:searchSuggestIntentAction="android.intent.action.VIEW">
</searchable>
In AndroidManifest.xml I've added
<activity android:name=".ItemSearch" android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
For this type of dropdown suggestion functionality you would use AutoCompleteTextView.
Example usage below:
In your layout file:
<AutoCompleteTextView
android:id="#+id/auto_complete_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/key"/>
In a resource file such as arrays.xml or strings.xml:
<string-array name="suggestions">
<item>January</item>
<item>February</item>
<item>March</item>
...
</string-array>
In your fragment or activity:
AutoCompleteTextView autoCompleteTv;
...
AutoCompleteTextView autoCompleteTv = (AutoCompleteTextView) view.findViewById(R.id.auto_complete_tv);
autoCompleteTv.setAdapter(ArrayAdapter.createFromResource(view.getContext(), R.array.suggestions, android.R.layout.simple_dropdown_item_1line));

ArrayAdapter<Button> displays buttons and object reference behind it in ListView

this is my first "project" with android and I'm trying to make a single-activity app that displays a list of buttons using a listview. For some reason my ArrayAdapter displays the button correctly but behind it, it displays the object reference. So when I debug it using my phone, I see a button and right behind it its object reference.
My activity looks like this:
package com.example.madelenko.showcase;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
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);
ArrayList<Button> projectList =
new ArrayList<Button>();
Button button1 = new Button(this);
Button button2 = new Button(this);
button1.setText("Spotify Streamer");
button2.setText("Scores App");
projectList.add(button1);
projectList.add(button2);
ArrayAdapter<Button> adapter =
new ArrayAdapter<Button>(this,R.layout.element_listview_layout,
R.id.list_item_string,projectList);
ListView listView = (ListView)findViewById(R.id.buttonListView);
listView.setAdapter(adapter);
}
#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);
}
}
My button element layout looks like this:
<?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">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold"
android:text=""/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/projectButton"
android:text="Hello world!"
android:layout_alignTop="#+id/list_item_string"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Finally, my listview looks like this:
<FrameLayout 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="com.example.madelenko.showcase.MainActivityFragment"
tools:showIn="#layout/activity_main">
<ListView
android:layout_width="wrap_content"
android:layout_height="401dp"
android:id="#+id/buttonListView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="My nanodegree apps!"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal|top" />
</FrameLayout>
Please, be patient with this newbie!
ArrayAdapter<Button> is not a recommended pattern. The adapter is supposed to be adapting model objects, whether those are trivial (e.g., ArrayAdapter<String>) or more complex (e.g., ArrayAdapter<Invoice>).
So, in this case:
You are creating an ArrayList<Button>, but those buttons will never be shown on the screen
You are inflating a layout for the rows that contains a TextView and a Button; those Button widgets will be the ones that are shown
You are telling ArrayAdapter to bind the String representation of the Button (from a call to toString() from the ArrayList to the list_item_string TextView in the row, when you create your ArrayAdapter<Button> instance
Also note that it is rather unusual to see buttons in ListView rows, since the user can click on the ListView rows themselves.
If you want to have a ListView with two rows for your two strings, you can do something like this:
public class ListViewDemo extends ListActivity {
private static final String[] items={"Spotify Streamer", "Scores App"};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
}
}

Android Listview Hides Titlebar

I'm trying to make an app - it has 3 activities. The first 2 are listviews in linear layouts, and each of them prevents the title bar from showing up. By title bar I mean the section that is normally at the top of an activity which displays the activity's name as well as an option setting. My third activity is not a listview, and displays the title bar normally, which leads me to think it may be a problem with my listviews.
The xml for my first page is:
<LinearLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".SelectClass">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
My java class doesn't do much to the display, although it does set an array adapter and an onClick listener. If those are necessary to understand what's going on then let me know and I'll post them. I appreciate any help or clues. Thank you!
EDIT: first page's java:
package com.example.graeme.dnd5echaracterroller;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.view.View;
import android.widget.TextView;
public class SelectClass extends ListActivity {
private static String classString;
public static void setClassString(String classString) {
SelectClass.classString = classString;
}
public static String getClassString() {
return classString;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<>(getListView().getContext(),
R.layout.classlayout, R.id.classname, classes);
getListView().setAdapter(classAdapter);
//Set on click listener to get selected class item
AdapterView.OnItemClickListener itemClickedHandler = new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
//Start a new intent headed to selectRoll, fill it with the class string selected
Intent sendClassIntent = new Intent(SelectClass.this, SelectRoll.class);
//Each list item has an image, and text
//First grab the list item, then grab the text from it
LinearLayout ll = (LinearLayout)v;
TextView tv = (TextView)(ll).findViewById(R.id.classname);
setClassString((String)(tv.getText()));
startActivity(sendClassIntent);
}
};
getListView().setOnItemClickListener(itemClickedHandler);
}
#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_select_class, 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);
}
}
You should modify you first activity as this structure
public class SelectClass extends AppCompatActivity {
...
private ListView mListView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_class);
// Initialize the lisview
mListView = (ListView) findViewById(R.id.lisview_id); // lisview id
//Initialize the available class choices
final String[] classes = {"Barbarian","Bard","Cleric","Druid",
"Fighter","Monk","Paladin","Ranger","Rogue","Sorcerer",
"Warlock", "Wizard"};
ArrayAdapter<String> classAdapter = new ArrayAdapter<> (this,
R.layout.classlayout, R.id.classname, classes); // update
mListView.setAdapter(classAdapter);
...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
....
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
.....
}
}
And in the ListView of first activity
<ListView
android:id="#+id/lisview_id" // use this id for initialize listview
android:layout_width="match_parent"
android:layout_height="match_parent">
Hope this help
I think that the problem is not the ListView, normally it is hided because of the style you have set in your manifest. This is what you have in the main activity inside manifest.xml:
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
the android:theme="#style/AppTheme" on the listView activity must be set as the Apptheme that shows the "Title bar".
Hope this helps

button to show an image android app

I would like to make a simple app with a button that shows a picture when pressed.
Here is what I've written.
manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:theme="#style/AppTheme"
android:name="Activityfullscreen"></activity>
</application>
main:
package com.mycompany.button_show;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent inf=new Intent(MainActivity.this,Activityfullscreen.class);
startActivity(inf);
}
});
}
#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);
}
}
.java for the second activity:
public class Activityfullscreen extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
ImageView img = (ImageView) findViewById(R.id.widget45);
img.setBackgroundResource(R.drawable.aa);
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button_send"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<TextView
android:id="#+id/widget45"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
</LinearLayout>
activity full screen:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/widget45"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
styles:
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Material.Light">
<!-- Customize your theme here. -->
</style>
When I run, everything is fine, but when I launch the app I get the following error:
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
Where is my mistake?
In Style.xml, you need to use AppCompat Theme - (RECOMMENDED)
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.AppCompat.Light">
<!-- Customize your theme here. -->
</style>
The above theme is Material Light theme.
Otherwise, you can leave AppCompat(But I don't recommend this as AppCompat is used for Material themes for lower Android versions like Jellybean, Honeycomb and Gingerbread) by using this code in Main - (NOT RECOMMENDED)
public class MainActivity extends Activity { // Changed from AppCompatActivity to just Activity
... Enter the code you use here
}
Change this too if you use the NOT RECOMMENDED method -
public class Activityfullscreen extends Activity { // Changed from AppCompatActivity to just Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
ImageView img = (ImageView) findViewById(R.id.widget45);
img.setBackgroundResource(R.drawable.aa);
}
If you like this answer, please mark it as selected.
PS - Material.light is available only on Android 4.4 (Kitkat) +

Android application restarts when opened by clicking the application icon

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
}
}

Categories

Resources