Using a toggle button to start and stop a menu item - java

This is the code inside of my MainActivity.java:
I am trying to use a toggle button to toggle a menu item to be on and off. The menu item when checked sets the background to red. When the item is not selected the background color is default. I am new to java so I am unsure what to put in the if and else statement under onCheckedChange. Any suggestions would help.
Thanks
import android.graphics.Color;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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.Button;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button showFragBut = (Button)findViewById(R.id.button);
showFragBut.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
String butText = showFragBut.getText().toString();
FragmentManager fg = getSupportFragmentManager();
FragmentTransaction ft = fg.beginTransaction();
if (butText.equals("Add fragment")){
Frag1 frag = new Frag1();
ft.add(R.id.dyframe, frag, null);
ft.addToBackStack(null);
ft.commit();
showFragBut.setText("Remove fragment");
} else {
getSupportFragmentManager().popBackStackImmediate();
showFragBut.setText("Add fragment");
}
MenuItem redMenuItem = (MenuItem)findViewById(R.id.menu_red);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton4);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
}
#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.
ConstraintLayout mainLayout = (ConstraintLayout)findViewById(R.id.content1);
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id){
case R.id.action_settings:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
Toast.makeText(getApplicationContext(), "Setting is clicked", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_red:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
mainLayout.setBackgroundColor(Color.RED);
return true;
case R.id.menu_green:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
mainLayout.setBackgroundColor(Color.GREEN);
return true;
}
return super.onOptionsItemSelected(item);
}
}
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:id="#+id/content1"
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">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="128dp"
android:layout_marginTop="116dp"
android:text="#string/button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Add Fragment" />
<FrameLayout
android:id="#+id/dyframe"
android:layout_width="185dp"
android:layout_height="63dp"
android:layout_marginStart="128dp"
android:layout_marginTop="44dp"
android:textAlignment="center"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button"/>
<ToggleButton
android:id="#+id/toggleButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="148dp"
android:layout_marginBottom="110dp"
android:text="#string/togglebutton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
<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="com.example.brettbanich.menuactivity.MainActivity">
<group android:checkableBehavior="single" >
<item
android:id="#+id/menu_red"
android:title="#string/red"
app:showAsAction="never" />
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</group>
</menu>

I think that this should work:
public void setColor(int color, boolean checked) {
ConstraintLayout mainLayout = (ConstraintLayout)findViewById(R.id.content1);
mainLayout.setBackgroundColor(color);
redMenuItem.setChecked(checked);
}
and for the toggle:
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
setColor(Color.GREEN, true);
} else {
setColor(Color.RED, false);
}
}
});
I'm not sure if the colors are swapped or not, the idea is something like this. I assume that the code in setColor() that you used in the onOptionsImetSelected() works as you expect.

Related

Handling of pushing menu item. Android

I have the following code:
MainActivity.java:
package asus.example.com.fitnessapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_items,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.home:
textView.setText("Home");
return true;
case R.id.notification:
textView.setText("Notification");
return true;
case R.id.profile:
textView.setText("Profile");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
activity_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"
tools:context=".MainActivity">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="52dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/nav_items"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"/>
</android.support.constraint.ConstraintLayout>
nav_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/home"
android:title="#string/home"
android:icon="#drawable/home" />
<item
android:id="#+id/notification"
android:title="#string/notifications"
android:icon="#drawable/notification" />
<item
android:id="#+id/profile"
android:icon="#drawable/person"
android:title="#string/profile" />
</menu>
When user clicks on any element of the bottom navigation bar the program should add to the textview the name of this element of menu. That's why there's the following lines in code, such as textView.setText("Home"); and other. But when user clicks on any elements, there's nothing shows int textview. What's the matter?
You are using a BottomNavigationView not a menu. You need to implement the BottomNavigationView.OnNavigationItemSelectedListener like this:
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
and then you need to set the listener in the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
BottomNavigationView bottomNav = findViewById(R.id.bottomNav);
bottomNav.setNavigationItemSelectedListener(this);
}
For this to work you need to add android:id="#+id/bottomNav" to your layout file:
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomNav"
android:layout_width="match_parent"
android:layout_height="52dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/nav_items"/>
And lastly the method to handle the OnNavigationItemSelectedListener event:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()){
case R.id.home:
textView.setText("Home");
return true;
case R.id.notification:
textView.setText("Notification");
return true;
case R.id.profile:
textView.setText("Profile");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You will not need onOptionsItemSelected() or onCreateOptionsMenu() if you just want to use the BottomNavigationView.

Add options menu to QR reader application in Android Studio?

I'm learning to code apps for android and I'm trying to code an app that reads QR codes, but I want to add an options menu. I have a small code that does it, but when I try to add it the QR reader app the menu does not show. Can you tell me what is wrong with what I have so far?
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.view.View;
import android.app.AlertDialog;
import android.util.Log;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class MainActivity extends Activity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// Here I added the menu to the qr app
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Here ends the part of the menu
public void onClick(View v){
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan result");
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/item1"
android:title="Item 1"/>
<item android:id="#+id/item2"
android:title="Item 2"/>
<item android:id="#+id/item3"
android:title="Item 3"/>
</menu>
activity_main.xml
<?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">
<GridLayout
android:layout_width="match_parent"
android:layout_height="114dp">
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_row="3"
android:onClick="onClick"
android:text="Scan QR" />
</GridLayout>
</LinearLayout>
I know that the options menu works by itself, because I tested alone as a different app, and also the qr reader works by itself, but if I try to combine them the menu is not there. I'm a newbie on coding android apps, so I will appreciate your guidance. Thanks
your menu name you supplied is menu.xml but instead you are giving getMenuInflater().inflate(R.menu.main, menu);
you should replace
getMenuInflater().inflate(R.menu.main, menu);
with
getMenuInflater().inflate(R.menu.menu, menu);

I'm having a trouble creating this new activity - Udacity Project Sunshine Lesson 3

Because the class is somewhat old, and the IDE changed so much, i'm struggling a bit trying to do the same steps of the class.
I have created my Intent and i can send it by clicking on the ListView Item. Then it switches activities from the MainActivity to the DetailActivity. Yet when the DetailActivity is displayed (using DetailActivityFragment) the toolbar disappears. I compared XML's and made some improvements but now the toolbar isn't populated like the previous toolbar. The activity also "fills" the notification bar (the bar that extends to the drawer).
Question is, what am I doing wrong and what can i do to replicate the MainActivity toolbar to the new DetailActivity?
MainActivity.java
package com.example.diomonogatarilaptop.sunshine;
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, "Something", 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;
}
if (id == R.id.action_refresh) {
MainActivityFragment.FetchWeatherTask weatherTask = new MainActivityFragment.FetchWeatherTask();
weatherTask.execute("Buraca");
return true;
}
return super.onOptionsItemSelected(item);
}
}
DetailActivity.java:
package com.example.diomonogatarilaptop.sunshine;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container_detail, new DetailActivityFragment())
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_detail);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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 static class DetailActivityFragment extends Fragment {
TextView textView;
public DetailActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent =getActivity().getIntent();
View rootView =inflater.inflate(R.layout.fragment_detail, container, false);
if(intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
textView= (TextView) rootView.findViewById((R.id.detail_text));
textView.setText(forecastStr);
}
return rootView;
}
}
}
Activity_detail.xml:
<android.support.design.widget.CoordinatorLayout 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"
android:id="#+id/container_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame">
<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_detail"
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_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_detail"
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.support.design.widget.CoordinatorLayout>
Content_detail.xml:
<fragment 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/fragment"
android:name="com.example.diomonogatarilaptop.sunshine.DetailActivity$DetailActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_detail"
/>
Fragment_detail.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="com.example.diomonogatarilaptop.sunshine.DetailActivity$DetailActivityFragment"
tools:showIn="#layout/activity_detail">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="New Text"
android:id="#+id/detail_text"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Some ScreenCaptures from debugging on my mobile:
MainActivity
DetailActivity Where the bug happens

ActionBar won't show up on new Activity

I am following the Android Development tutorials on Udacity and I have came across a problem in the app that I can't seem to work out how to fix.
I have created the new activity, and the Intent works perfectly fine in loading the new activity, the only problem is that when the second activity loads there is no actionbar that loads. Any Ideas?
MainActivity.java
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.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);
}
}
DetailActivity.java
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(forecastStr);
}
return rootView;
}
}
}
activity_detail.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame" />
content_detail.xml
<fragment 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/fragment"
android:name="com.example.turnergasoil.sunshine.DetailActivityFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_detail" />
fragment_detail.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="com.example.turnergasoil.sunshine.DetailActivityFragment"
tools:showIn="#layout/activity_detail">
<TextView
android:id="#+id/detail_text"
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
When changing the XML and Java file to include the toolbar, the frame layout and toolbar now overlap each other. See below.
When changing the XML and Java file to include the toolbar, the frame layout and toolbar now overlap each other. See below.
Should add Toolbar into the second activity's layout, and
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
EDIT
activity_detail.xml should be like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.sunshine.app.DetailActivity"
tools:ignore="MergeRootFrame">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/actionbar_height"
android:background="?attr/colorPrimary" />
</FrameLayout>

Select music through Spinner and Play

What i want to do is to add a spinner and a button, in spinner 2 songs are placed when i selected a song it plays and same as for other one but when i run this code it will do nothing just display a spinner and button and i only select a song and when i clicked a play button it do no respond.
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
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.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
public int soundSelection;
MediaPlayer mp;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
btn=(Button)findViewById(R.id.button1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.soundEntries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (soundSelection) {
case 1:
if (mp != null && mp.isPlaying())
mp = MediaPlayer.create(MainActivity.this, R.raw.bewafa);
mp.start();
mp.setVolume(100,100);
mp.setLooping(true);
Toast t = Toast.makeText(MainActivity.this,"bewafa",Toast.LENGTH_LONG);
t.show();
break;
case 2:
// if(mp.isPlaying())
mp = MediaPlayer.create(getApplicationContext(), R.raw.dildobaa);
mp.start();
Toast th = Toast.makeText(getApplicationContext(), "dildobaa", Toast.LENGTH_LONG);
th.show();
break;
}
}
});
}
/*Spinner Functions*/
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
soundSelection=(Integer)parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
#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);
}
}
This is the Xml code:
<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=".MainActivity">
<Spinner
android:layout_width="wrap_content"
android:entries="#array/soundEntries"
android:layout_height="wrap_content"
android:id="#+id/spinner1">
</Spinner>
<Button
android:layout_width="wrap_content"
android:text="Play"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:id="#+id/button1" />
This is Strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string-array name="soundEntries">
<item>bewafa</item>
<item>dildobaa</item>
</string-array>
Do below changes to your code:
implement AdapterView.OnItemSelectedListener:
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {
Change switch cases to 0 and 1. (The count starts with 0)
Comment out the line: if (mp != null && mp.isPlaying())
Change onItemSelected() callback method to:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
soundSelection = pos;
}

Categories

Resources