I'm having some issues with a searchView in my Fragments.
So, when I'm pressing the search_icon within the actionbar, the method searchClick() is executed.
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/search"
android:title="#string/app_name"
android:icon="#drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:onClick="searchClick"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
/>
</menu>
MainActivity.Java
package formelhelfer5_10.formelhelfer5_10;
import android.app.SearchManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SearchView.OnCloseListener, SearchView.OnQueryTextListener
{
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent sIntent = getIntent();
if (Intent.ACTION_SEARCH.equals(sIntent.getAction())) {
String query = sIntent.getStringExtra(SearchManager.QUERY);
}
}
public void searchClick(MenuItem item){
Fragment frag = new Results();
Fragment rem = new FaecherFrag();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(rem).add(R.id.FragFaecher,frag).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, 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.setOnCloseListener(this);
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onClose() {
Fragment frag = new Results();
Fragment rem = new FaecherFrag();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.remove(rem).add(R.id.results,frag).commit();
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
TextView t = (TextView) findViewById(R.id.tv);
if (query.isEmpty()){return false;}else
{t.setText(query);}
return false;
}
}
searchClick then removes the current Fragment
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"
android:id="#+id/main_content"
tools:context="formelhelfer5_10.formelhelfer5_10.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.CoordinatorLayout>
content_main.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_content"
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="formelhelfer5_10.formelhelfer5_10.MainActivity"
tools:showIn="#layout/activity_main"
android:background="?android:colorBackground">
<fragment
android:id="#+id/FragFaecher"
android:name="formelhelfer5_10.formelhelfer5_10.FaecherFrag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
FaecherFrag.Java
package formelhelfer5_10.formelhelfer5_10;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
public class FaecherFrag extends ListFragment {
sql sqlo = new sql();
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] m_fach = sqlo.getFaecher(getContext());
ListAdapter adptFach =
new ArrayAdapter<>(
getActivity(), android.R.layout.simple_list_item_1, m_fach);
setListAdapter(adptFach);
//Array m_fach wird als Liste angezeigt
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
transFach(position);
//uebergibt die Position des Fachs an die naechste Methode
}
private void transFach(int position){
String[] m_fach = sqlo.getFaecher(getContext());
String sql_fach = m_fach[position]; //String für die SQL-Abfrage. Zeigt welches Fach ausgewaehlt wurde
String[] m_thema = sqlo.getThemen(getContext(), sql_fach);
Intent toThemen = new Intent(getActivity(),Themen.class);
toThemen.putExtra("thema_key",m_thema);
startActivity(toThemen);
}
}
and adds another Fragment that displays the query in a TextView
fragment_results.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="#+id/results"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="?android:colorBackground" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv"
android:text="Text"
android:textAppearance="?android:textAppearanceLarge"
android:textStyle="bold"/>
</RelativeLayout>
Results.Java
package formelhelfer5_10.formelhelfer5_10;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Results extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_results, container, false);
return rootView;
}
}
My first Issue is, that when I submit the query, the second Fragment (fragment_results) "disappears" and the normal ListFragment (activity_main) appears. I don't know how to solve this.
The second Issue is, that when I dismiss/close the Search Widget, I expect the OnCloseListener to remove the second Fragment (fragment_results) and show the ListFragment (activity_main). Although I implemented this in the OnCloseListener, nothing happens. Or am I confusing the OnCloseListener with something else?
I would be glad, if you can help me with this.
For first problem, you are setting onClick in xml for menu item. This is wrong and will not call. Please implement onItemMenuSelected using https://developer.android.com/guide/topics/ui/menus.html#RespondingOptionsMenu
Related
I made this switch on one of my fragment to switch from the dark theme to light theme. The only problem is that when I leave fragment with the switch on when I go back to the fragment, the switch is off instead of being on like I left it.
Here are the images.
When I go on the fragment: Fragment Switch Off
When I flip the switch: Fragment Switch On
Then I leave the Fragment, then come back to the Fragment: Fragment Switch off while supposed to be on
Her is my code:
SettingsFragment.java:
package com.barzalou.lpapineau.test.ui.settings;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;
import com.barzalou.lpapineau.test.R;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import java.util.Objects;
public class SettingsFragment extends Fragment {
private SettingsViewModel settingsViewModel;
private CheckedChangeCallback callback = null;
public void onAttach(final Activity activity) {
super.onAttach(activity);
if (activity instanceof CheckedChangeCallback) {
this.callback = (CheckedChangeCallback) activity;
}
}
public void onDetach() {
super.onDetach();
callback = null;
}
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
settingsViewModel = ViewModelProviders.of(this).get(SettingsViewModel.class);
View root = inflater.inflate(R.layout.fragment_settings, container, false);
final TextView textView = root.findViewById(R.id.text_settings);
settingsViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final Switch DarkMode = (Switch) getView().findViewById(R.id.DarkModeSwitch);
final boolean DarkModeVal = DarkMode.isChecked();
Log.d("Dark Mode Checked Value", String.valueOf(DarkModeVal));
DarkMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
callback.onCheckedChange(isChecked);
}
});
}
}
SettingsViewModel.java:
package com.barzalou.lpapineau.test.ui.settings;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class SettingsViewModel extends ViewModel {
private MutableLiveData<String> mText;
public SettingsViewModel() {
mText = new MutableLiveData<>();
mText.setValue("Settings");
}
public LiveData<String> getText() {
return mText;
}
}
CheckedChangeCallback.java:
package com.barzalou.lpapineau.test.ui;
public interface CheckedChangeCallback {
void onCheckedChange(boolean isChecked);
}
MainActivity.java:
package com.barzalou.lpapineau.test;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.audiofx.Equalizer;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.Switch;
import com.barzalou.lpapineau.test.ui.CheckedChangeCallback;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class MainActivity extends AppCompatActivity implements CheckedChangeCallback {
private AppBarConfiguration mAppBarConfiguration;
#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();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#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 onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_exit) {
finish();
System.exit(0);
}
return false;
}
public void onCheckedChange(boolean isChecked) {
Switch DarkMode = findViewById(R.id.DarkModeSwitch);
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
Log.d("Dark Mode Switch State", "On");
DarkMode.setChecked(true);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
Log.d("Dark Mode Switch State", "Off");
DarkMode.setChecked(false);
}
}
}
fragment_settings.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:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#fff"
android:padding="10dp"
tools:context=".ui.home.HomeFragment">
<!-- Title -->
<TextView
android:id="#+id/text_settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:shadowColor="#bfbfbf"
android:shadowDx="5"
android:shadowDy="5"
android:shadowRadius="0.01"
android:text="#string/this_is_home"
android:textAlignment="center"
android:textColor="#000"
android:textSize="34sp" />
<!-- ...... -->
<!-- Card_View Settings -->
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" />
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_inner"
android:layout_width="match_parent"
android:layout_height="90dp"
android:layout_gravity="center"
android:translationY="60dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:elevation="4dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="#string/Settings"
android:textSize="22sp"/>
<Switch
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:id="#+id/DarkModeSwitch"
android:text="#string/dark_mode"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- .................. -->
<!-- Card_View 2 -->
<androidx.cardview.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginRight="3dp"
android:layout_marginEnd="3dp"
card_view:cardBackgroundColor="#f5f5f5"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="3dp" />
<androidx.cardview.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view_2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:translationY="170dp"
android:layout_marginLeft="3dp"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="#d3d3d3"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" >
</androidx.cardview.widget.CardView>
<!-- ........... -->
</RelativeLayout>
How can this be fixed? I want it to stay flipped while the dark theme is on.
Thanks!
Because fragment recreated, the switch result is lost. So you should save the switch result. For example, SharedPreference.
In my Android App, I want to play set of some songs. Here with the help of my code I can play songs by clicking individually. But I can't make play the next song continuously once the song gets finished using Media Player. And also here I can't make a shuffle song also. Here Looping a same song only possible. But my requirement is to play the next song automatically once the firstly played song gets finished. Here is my code
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="65dp"
android:padding="10dp"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/listView"/>
</LinearLayout>
</ScrollView>
<include
layout="#layout/app_bar_homepage"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_homepage"
app:menu="#menu/activity_homepage_drawer" />
</android.support.v4.widget.DrawerLayout>
Java Code:
package com.musicapp;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.constraint.Group;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class MusicActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView listView;
List<String> list;
ListAdapter adapter;
MediaPlayer mediaPlayer;
private int currentSongIndex = 0;
View previousSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
listView = findViewById(R.id.listView);
list=new ArrayList<>();
Field[] fields = R.raw.class.getFields();
for(int i=0;i<fields.length;i++){
list.add(fields[i].getName());
}
adapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
listView.setPadding(0,20,0,0);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(mediaPlayer!=null){
mediaPlayer.release();
}
int resID = getResources().getIdentifier(list.get(i),"raw",getPackageName());
mediaPlayer = MediaPlayer.create(MusicActivity.this,resID);
mediaPlayer.start();
if (previousSelectedItem!=null) {
previousSelectedItem.setBackgroundColor(Color.WHITE);
}
previousSelectedItem=view;
view.setBackgroundResource(R.drawable.bg_with_color);
}
});
}
Could anybody help me?
i have tried the all the suggestions for this. All that answers are changing the fragment from a activity but here is the difference in my question. i am trying to change one fragment to another fragment from the first fragment.Please help me .
i have a fragment which contains dynamic buttons.please find the image [![enter image description here][1]][1]
If the user clicks any of the button i want to show some stack cars for the same.see the image [![enter image description here][2]][2]
Ok this is my requirement. My problem is i have one activity which contains the bottom navigation bar names as ShowDashBoardActivity
ShowDashBoardActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.yourname.R;
import com.yourname.fragments.DashBoardJobList;
import com.yourname.fragments.DashBoardOne;
import com.yourname.fragments.DashBoardTaskBubble;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarFragment;
import butterknife.Bind;
public class ShowDashBoardActivity extends AppCompatActivity {
private BottomBar bottomBar;
LinearLayout CardAspirationLayout,TextCardAspirationLayout;
DashBoardOne _DashBoardOne;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_dash_board_activity);
context=getApplicationContext();
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
View view =getSupportActionBar().getCustomView();
/*ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});*/
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
new BottomBarFragment(DashBoardOne.newInstance("Content for Dashboard."), R.drawable.dashboard, "Dashboard"),
new BottomBarFragment(DashBoardTaskBubble.newInstance("Content for Task."), R.drawable.task, "Task"),
new BottomBarFragment(DashBoardJobList.newInstance("Content for Job."), R.drawable.job, "Job")
);
TextCardAspirationLayout=(LinearLayout) findViewById(R.id.TextCardAspirationLayout);
bottomBar.setActiveTabColor("#C2185B");
BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(2, "#E91E63", 4);
unreadMessages.show();
unreadMessages.setAnimationDuration(200);
unreadMessages.setAutoShowAfterUnSelection(true);
// bottomBar.useDarkTheme(true);
}
}
show_dash_board_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/slidetwo"
xmlns:tools="http://schemas.android.com/tools" >
</FrameLayout>
The navigation drawer is working perfect. the in the DashBoardTaskBubble.java it is fragment i am drawing dynamic bubble to show like picture 1.
DashBoardTaskBubble.java
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.panenviron.R;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.tint;
public class DashBoardTaskBubble extends Fragment {
private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
public DashBoardTaskBubble() {
}
public static DashBoardTaskBubble newInstance(String text) {
Bundle args = new Bundle();
args.putString(STARTING_TEXT, text);
DashBoardTaskBubble dashBoardTaskBubble = new DashBoardTaskBubble();
dashBoardTaskBubble.setArguments(args);
return dashBoardTaskBubble;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_bubble, container, false);
final RelativeLayout workViewLayout = (RelativeLayout)view.findViewById(R.id.workView);
int iNumberOfButtons = 6; // no of bubble create function to fetch no of bubble from db
// create a function to get color from db now give static
String[] colourList = new String[] { "#ffaa00","#32CD32","#0000FF"};
Button[] dynamicButtons = new Button[iNumberOfButtons];
List<String> tempColouersList= new ArrayList<String>();
for (int i = 0; i < iNumberOfButtons; i++) {
dynamicButtons[i] = new Button(getActivity());
dynamicButtons[i].setText("+"+i+5);
dynamicButtons[i].setId(i);
dynamicButtons[i].setTextSize(15.0f);
dynamicButtons[i].setBackgroundResource(R.drawable.round_button);
if(i==0){
RelativeLayout.LayoutParams paramsButton =
new RelativeLayout.LayoutParams(350,350);
paramsButton.setMargins(50,0,0,0);
dynamicButtons[0].setLayoutParams(paramsButton);
tempColouersList.add(colourList[0]);
} else if(i==1){
RelativeLayout.LayoutParams paramsButton2 =
new RelativeLayout.LayoutParams(350,350);
paramsButton2.setMargins(700,10,0,0);
dynamicButtons[1].setLayoutParams(paramsButton2);
tempColouersList.add(colourList[1]);
} else if(i==2){
RelativeLayout.LayoutParams paramsButton3 =
new RelativeLayout.LayoutParams(350,350);
paramsButton3.setMargins(400,250,0,0);
dynamicButtons[2].setLayoutParams(paramsButton3);
tempColouersList.add(colourList[2]);
} else if(i==3){
RelativeLayout.LayoutParams paramsButton4 =
new RelativeLayout.LayoutParams(350,350);
paramsButton4.setMargins(50,450,0,0);
dynamicButtons[3].setLayoutParams(paramsButton4);
tempColouersList.add(colourList[1]);
} else if(i==4){
RelativeLayout.LayoutParams paramsButton5 =
new RelativeLayout.LayoutParams(350,350);
paramsButton5.setMargins(700,500,0,0);
dynamicButtons[4].setLayoutParams(paramsButton5);
tempColouersList.add(colourList[2]);
}else if(i==5){
RelativeLayout.LayoutParams paramsButton6 =
new RelativeLayout.LayoutParams(350,350);
paramsButton6.setMargins(350,700,0,0);
dynamicButtons[5].setLayoutParams(paramsButton6);
tempColouersList.add(colourList[0]);
}
ColorStateList tint = new ColorStateList(new int[][]{new int[0]}, new int[]{Color.parseColor(tempColouersList.get(i)) });
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && dynamicButtons[i] instanceof AppCompatButton) {
((AppCompatButton) dynamicButtons[i]).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(dynamicButtons[i], tint);
}
dynamicButtons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Log.e("im on","button clik");
} catch (Exception e) {
e.printStackTrace();
}
}
});
workViewLayout.addView(dynamicButtons[i]); // dynamicButtonsLinearLayout is the container of the buttons
}
return view;
}
public void replaceFragments( ) {
Log.e("im on","replaceFragments");
//Fragment fragment = null;
try {
//fragment = (Fragment) TaskCardListShow.newInstance();
/*TaskCardListShow nextFrag= new TaskCardListShow();
this.getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, nextFrag)
.addToBackStack(null)
.commit();*/
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = https://i.stack.imgur.com/J75iJ.pngmFragmentManager.beginTransaction();
TaskCardListShow mFragment = new TaskCardListShow();
//mFragmentTransaction.replace(R.id.fragmentContainer, mFragment);
mFragmentTransaction.add(R.id.fragmentContainer, mFragment);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
} catch (Exception e)
{ e.printStackTrace(); }
// Insert the fragment by replacing any existing fragment FragmentManager
// fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
}
fragment_task_bubble.xml
<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:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/slidetwo">
<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="0dp"
android:layout_weight="12"
android:background="#color/white">
</LinearLayout>
<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="0dp"
android:layout_weight="88"
android:orientation="vertical"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="3dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20dp">
<View
android:layout_width="98dp"
android:gravity="center_horizontal"
android:layout_height="4dp"
android:background="#android:color/holo_red_dark"
android:id="#+id/normalViewSeparator"
/>
</LinearLayout>
<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="wrap_content"
android:layout_weight="30"
android:orientation="vertical"
android:id="#+id/workView"
android:background="#color/white">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
The bubble drawing is also working perfect. Here i trying to add some features like if a user clicks a button i want to show the stack cards like picture 2
I am thinking to display the task cards in fragment . I dont know how to navigate one fragment to another fragment.
TaskCardListShow.java FRAGMENT
package com.panenviron.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.panenviron.R;
public class TaskCardListShow extends Fragment {
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
Log.e("im on","TaskCardListShow");
return view;
}
}
task_card_list_show.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:id="#+id/fragment_task_card_list_show"
style="#style/Animation.AppCompat.Dialog">
<TextView
android:text="Im on task fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_weight="1" />
</LinearLayout>
i tried the above replaceFragments( ) custom function. But it is replaces the fragment but it is not removing the first fragment. How can do this.
Your are using support fragments (android.support.v4.app.Fragment) with native fragmentmanager - Activity.getFragmentManager(). Instead you have to use support fragmentmanager - AppCompatActivity.getSupportFragmentManager().
I really wish android tools would handle this annoying situation better.
inside the fragment you have to call getActivity().getSupportFragmentManager() instead of getFragmentManager. so you have to give like this "getActivity().getSupportFragmentManager().beginTransaction()" in the fragment transaction. after that you can replace simply like already done
I am using toolbar to make a customized action bar. I have a class called BaseActivity which I inherit in all other activity. It merges the toolbar to actionbar. But the thing is I ma not getting the toolbar icons and titles visible.
Here's my BaseActivity:
package com.meroanswer.classes;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.meroanswer.R;
public abstract class BaseActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primary_dark));
}
}
}
protected abstract int getLayoutResource();
protected void setActionBarIcon(int iconRes) {
try{
toolbar.setNavigationIcon(iconRes);
}
catch (NullPointerException e){
Log.d("Roshan", "Exception");
}
}
}
Here's my derived page code
package com.meroanswer;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.meroanswer.DrawerAdapter;
import com.meroanswer.MainActivity;
import com.meroanswer.R;
import com.meroanswer.SlidingTabLayout;
import com.meroanswer.ViewPagerAdapter;
import com.meroanswer.classes.BaseActivity;
import com.meroanswer.classes.Helper;
import com.meroanswer.connection.AsyncPut;
import com.meroanswer.connection.Connection;
import com.meroanswer.database.model.Stream;
import com.meroanswer.database.model.User;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SettingsPage extends BaseActivity {
public WebView webview;
Helper helper;
Context context;
private String temp_str;
private DrawerLayout drawer;
Toolbar toolbar;
RecyclerView mRecyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager mLayoutManager;
ActionBarDrawerToggle mDrawerToggle;
DrawerLayout Drawer;
String TITLES[] = {
"Coupons",
"Upgrade to Premium",
"Rate us",
"Share App",
"Settings",
"About",
"Log out"
};
int ICONS[] = {
R.drawable.coupon,
R.drawable.premium,
R.drawable.star,
R.drawable.share,
R.drawable.settings,
R.drawable.about,
R.drawable.logout
};
String NAME = "A B";
String EMAIL = "a#b.com";
int PROFILE = R.drawable.profile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
getSupportActionBar().setIcon(R.drawable.ic_ab_drawer);
getSupportActionBar().setTitle("Settings");
helper = new Helper(context);
webview = (WebView) findViewById(R.id.dashboard_webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setUseWideViewPort(false);
settings.setLoadsImagesAutomatically(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
int android_version = android.os.Build.VERSION.SDK_INT;
if (android_version >= 11) {
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webview.addJavascriptInterface(new SettingsProvider(this, webview),
"Android");
webview.loadUrl("file:///android_asset/ma_html/setup.html");
drawer = (DrawerLayout) findViewById(R.id.drawer);
//drawer.setDrawerShadow(R.drawable.drawer_shadow, Gravity.START);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new DrawerAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
}
#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_settings_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawer.openDrawer(Gravity.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_settings_page;
}
}
}
and here's my layout resource file for the activity:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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:background="#color/white"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<WebView
android:id="#+id/dashboard_webview"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</WebView>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ffffff"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
<!--<ListView
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/windowBackgroundColor"/>-->
</android.support.v4.widget.DrawerLayout>
menu file
<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.meroanswer.SettingsPage">
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
Do the following and check whether you can see changes:
Change the menu.xml as shown below:
<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.meroanswer.SettingsPage">
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="always" /> // This line has been changed from never to always
</menu>
In your onOptionsItemSelected method add the following part:
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this, "Settings button has been selected", Toast.Length_Long).show();
return true;
}
After these run the application and click on the settings text ion tool bar you will see a toast message.
Hope it helps.
My app crash when ever I try to run my program .This is the code I am using .
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void selectFrag(View view) {
Fragment fr;
if(view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
}else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
FragmentOne.java
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
FragmentTwo.java
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_one, container, false);
}
}
main_activity.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" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment No.1"
android:onClick="selectFrag" />
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.2" />
<fragment
android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fragment_one.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"
android:background="#00ffff">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="This is fragment No.1"
android:textStyle="bold" />
</LinearLayout>
The fragment_two.xml is also same as fragment_one.xml but in the TextView I am printing fragment no.2 instead of fragment no.1.
And in my AndroidManifest.xml file the min sdk version I am using is 11. Please guys enligthen me were I am going wrong and correct me .
I copied the code from this link
Since your package name is package name is com.example.fragmentstest, change this line:
android:name="com.javacodegeeks.android.fragmentstest.FragmentOne"
to
android:name="com.example.fragmentstest.FragmentOne"
in main_activity.xml