how to change the main layout by SideMenu - android

about : I just click the menu SideMenu
"Rate" or even other menu, and I want to change the main view that the right arrow shows, but how? and here is the source of github
case 0:
// int the case, click the menu : Rate (or even other menu)
/**
* If I click the menu in the picture : Rate
* I want to change the main layout that the right arrow shows
* but how ?
* 1: what to do with the content view ?
* 2: or what to with the following code ?
*/
break;

You seem to have 2 options:
Intent to a new Activity which has your required functionality
Intent rateIntent = new Intent(CurrentActivity.this, NextActivity.class));
startActivity(rateIntent);
If you use fragments, you will need to replace your current fragment, you can use the FragmentManager for this type of app navigation
NextFragment nextFrag= new NextFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
.addToBackStack(null)
.commit();
https://developer.android.com/reference/android/app/FragmentManager.html
https://developer.android.com/reference/android/content/Intent.html
Hope this helps

MainActivity xml
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="fill_parent">
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/navdrawer"
android:layout_width="#dimen/navdrawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:drawSelectorOnTop="false">
</ListView>
</android.support.v4.widget.DrawerLayout>
We add fragment in framelayout when click on listview item.
Create fragments
StopAnimationFragment
StartAnimationFragment
ChangeColorFragment
GitHubPageFragment
ShareFragment
RateFragment
package com.ikimuhendis.ldrawer.sample;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.ikimuhendis.ldrawer.ActionBarDrawerToggle;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;
public class SampleActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerArrowDrawable drawerArrow;
private boolean drawerArrowColor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
ActionBar ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.navdrawer);
drawerArrow = new DrawerArrowDrawable(this) {
#Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
drawerArrow, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
String[] values = new String[]{
"Stop Animation (Back icon)",
"Stop Animation (Home icon)",
"Start Animation",
"Change Color",
"GitHub Page",
"Share",
"Rate"
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
mDrawerToggle.setAnimateEnabled(false);
drawerArrow.setProgress(1f);
//create Fragment and call this method
setNavigationFragments(new StopAnimationFragment());
break;
case 1:
mDrawerToggle.setAnimateEnabled(false);
drawerArrow.setProgress(0f);
//create Fragment and call this method
setNavigationFragments(new StopAnimationFragment());
break;
case 2:
mDrawerToggle.setAnimateEnabled(true);
mDrawerToggle.syncState();
//create Fragment and call this method
setNavigationFragments(new StartAnimationFragment());
break;
case 3:
if (drawerArrowColor) {
drawerArrowColor = false;
drawerArrow.setColor(R.color.ldrawer_color);
} else {
drawerArrowColor = true;
drawerArrow.setColor(R.color.drawer_arrow_second_color);
}
mDrawerToggle.syncState();
//create Fragment and call this method
setNavigationFragments(new ChangeColorFragment());
break;
case 4:
//create Fragment and call this method
setNavigationFragments(new GitHubPageFragment());
break;
case 5:
//create Fragment and call this method
setNavigationFragments(new ShareFragment());
break;
case 6:
//create Fragment and call this method
setNavigationFragments(new RateFragment());
break;
}
}
});
}
private void setNavigationFragments(Fragment fragment) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,fragment).commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}

Related

Navigation Drawer and action bar in all activity?

I have implemented actionbar and navigation drawer on all activity by extending base activity but when i use setcontent view in child activity navigation drawer doesn't works at how to solve this! Here is my code:
MainActivity which contains navigation drawer:
package first.service.precision.servicefirst;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class Main2Activity extends Activity {
public static ContactView contactView;
NewContacts newContacts;
public static LeadRequirementsView _LeadRequirements;
//public ContactView contactView;
protected DrawerLayout mDrawerLayout;
public static String mysting;
private ListView mDrawerList;
Button butonlead;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
protected ActionBarDrawerToggle mDrawerToggle;
// Title of the action bar
private String mTitle = "";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final ActionBar ab = getActionBar();
ab.show();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ab.setTitle(mTitle);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.open_drawer,
R.string.close_drawer) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplication(),
R.layout.drawer_list_item, R.id.title, getResources().getStringArray(R.array.option));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
ab.setHomeButtonEnabled(true);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#53A93F")));
// Enabling Up navigation
ab.setIcon(R.drawable.sfwhite);
ab.show();
ab.setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of options
String[] menuItems = getResources().getStringArray(R.array.option);
// Currently selected option
mTitle = menuItems[position];
// Fragment fragment = null;
// String tag = "";
switch (position) {
case 0:
Intent lead=new Intent(getApplicationContext(),LeadActivity.class);
startActivity(lead);
break;
case 1:
Intent opportunities=new Intent(getApplicationContext(),OpportunitiesActivity .class);
startActivity(opportunities);
break;
case 2:
Intent Accounts=new Intent(getApplicationContext(),AccountsActivity.class);
startActivity(Accounts);
break;
case 3:
Intent Contacts=new Intent(getApplicationContext(),Contacts.class);
startActivity(Contacts);
break;
case 4:
Intent Competitors=new Intent(getApplicationContext(), Competitors.class);
startActivity(Competitors);
break;
case 5:
Intent Acivity=new Intent(getApplicationContext(), Activitites.class);
startActivity(Acivity);
break;
case 6:
Intent Reports=new Intent(getApplicationContext(),ReportActivity.class);
startActivity(Reports);
break;
default:
break;
}
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
// int back=getFragmentManager().getBackStackEntryCount();
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
super.onBackPressed();
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Called whenever we call invalidateOptionsMenu()
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
/* #Override
public void data(String str, String sl) {
Accounts accounts=(Accounts)getFragmentManager().findFragmentByTag("accounts");
accounts.datarecieve(str,sl);
}*/
/*#Override
public void dataTo(ContactView contactView) {
Contactss contactss=(Contactss)getFragmentManager().findFragmentByTag("contact");
contactss.dataTo(contactView);
}*/
/* #Override
public void DataTransfer(String e) {
}*/
//
// #Override
// public void DataTransfer(ArrayList<String> e) {
// Add obj=(Add)getFragmentManager().findFragmentById(R.id.frag_1);
// obj.GetlistContact(e);
// }
}
/* #Override
public void selectedvalue(String s) {
Add add=new Add();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame,add);
ft.commit();}
}
*/
Here is chlid activity which extends base activity
package first.service.precision.servicefirst;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class LeadActivity extends Main2Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super. setContentView(R.layout.activity_lead);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_lead, null, false);
mDrawerLayout.addView(contentView, 0);
ArrayList<NewsItem> listContact = GetlistContact();
ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(new CustomListAdapter(this, listContact));
}
private ArrayList<NewsItem> GetlistContact(){
ArrayList<NewsItem> contactlist = new ArrayList<NewsItem>();
NewsItem contact = new NewsItem();
for(int i=1;i<=30;i++) {
contact = new NewsItem();
contact.setHeadline("Yoge " +i);
contact.setReporterName("Yogeshwaran" + i);
contact.setLeadsource("Yogan" + i);
contact.setLeadStatus("open" + i);
contact.setLeadType("Business"+i);
contactlist.add(contact);
}
return contactlist;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, 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);
}
}
am trying to populate listview in child activity i can get the listview but navigation drawer is missing how to solve this!
For this purpose you can use to View Stub in your XML file, which will common for all Java files. Means you should make a separate XML (i.e write common code for all xml file into this one) and access this XML file in different-different java files (activity files).
You can better understand from below line of code.
Add following in your master/common XML file which contain to navigation drawer and action bar with View Stub.
<RelativeLayout
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/Home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_home"
tools:context="com.example.bhuvneshgautam.cityretails.HomeActivity">
<ViewStub
android:id="#+id/layout_stub"
android:inflatedId="#+id/message_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.75" />
</RelativeLayout>
now add below line of code in your each java file(activity java file)
in on Create
ViewStub stub = (ViewStub) findViewById(R.id.layout_stub);
stub.setLayoutResource(R.layout.home_content);
View inflated = stub.inflate();
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();
}
});
Now use to "R.layout.home_content" for passing to XML file name which contain to code which you want to different in different pages.Below is one file code of my project which contain to separate code which i want to different in that file.
In home_content.xml
<ImageView
android:id="#+id/Hpersonalcare"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/personalcare"
android:scaleType="centerCrop"/>
you have to use View Stub
<ViewStub
android:id="#+id/layout_stub"
android:inflatedId="#+id/message_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.75" />
in your MainActivity....
Main2Activity.java
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
.........................
#Override
protected void onCreate(Bundle savedInstanceState) {
.....................
ViewStub stub = (ViewStub) findViewById(R.id.lay_stub);
stub.setLayoutResource(R.layout.home_content);
View inflated = stub.inflate();
Toolbar toolbar = (Toolbar) findViewById(R.id.tlbar);
setSupportActionBar(tlbar);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
dont use setContentView(...) again, it overwrites this call in Main2Activity removing drawer. let your "main" Activity be abstract and create protected abstract int getCustomContentView(...) which will be available in all extending Activities, return id which you have currently passing inside setContentView and inflate it in parent and add to container in Drawer. it might be done inside OnCreate so after super you can call directly after findViewByIdin childs
public abstract class Main2Activity extends Activity {
protected abstract int getCustomContentViewResId();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
LinearLayout container = (LinearLayout) findViewById(R.id.drawer_container);
int layoutResourceId = getCustomContentView();
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View innerView = inflater.inflate(layoutResourceId , container, true);
//rest of code
}
}
Lead:
public class LeadActivity extends Main2Activity {
protected int getCustomContentViewResId(){
return R.layout.activity_lead;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_lead);
// this goes to getCustomContentViewResId
ListView lv = (ListView)findViewById(R.id.listView);
// inflating already done in super.onCreate by extended Main2Activity so you may call findViewById directly without setContentView
}
//rest of code
}

how to change the Title in Navigation Drawer

I would like that the title in the menu will change by the fragment name that was click. for the code below what i get is that, the actual title in each fragment is "Home" and its does not change. but i found that when i click on an item in the menu the title changing for a second and return back to the "Home" title. i implemented the ondrawer but still i don't know what could cause that.
my code:
package com.example.matant.gpsportclient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainScreen extends AppCompatActivity implements AsyncResponse {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DBcontroller dbController;
private ProgressDialog progress = null;
private SessionManager sm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sm = SessionManager.getInstance(this);
mTitle = mDrawerTitle = "Home";
DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void handleResponse(String resStr) {
try
{
if((this.progress!= null )&& this.progress.isShowing())
{
this.progress.dismiss();
}
}catch (final IllegalArgumentException e){
Log.d("Dialog error",e.getMessage());
}catch (final Exception e){
Log.d("Dialog error",e.getMessage());
}
finally {
this.progress = null;
}
Log.d("handleResponse", resStr);
if(resStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString(Constants.TAG_FLG);
switch (flg) {
case "user logged out":
{
sm.logoutUser();
break;
}
case "query failed": {
Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void sendDataToDBController() {
String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagReq);
nameValuePairList.add(userNameParam);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
this.progress = ProgressDialog.show(this, "Log Out",
"Logging out...", true,false);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0: //Home
fragment = new GoogleMapFragmentController();
break;
case 1: //Profile
fragment = new ProfileFragmentController();
break;
case 2: //Search Events
//fragment = new SearchEventFragmentController();
break;
case 3: //Create Events
fragment = new CreateEventFragmentController();
break;
case 4: //Manage Events
fragment = new ManageEventFragmentController();
break;
case 5: //Attending List
//fragment = new AttendingListFragmentController();
break;
case 6: //Recent Searches
//fragment = new RecentSearchesFragmentController();
break;
case 7: { //Log Out
logout();
finish(); //destroy the main activity
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void logout()
{
sendDataToDBController();
}
/*#Override
protected void onDestroy() {
super.onDestroy();
logout();
}*/
}
Set it for all your fragment. This should do the work!!
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.id.your_fragment_layout, container,
false);
getActivity().setTitle("<your title>");
return rootView;
}
try this:
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
}
Ok i found the problem, your answer was good and i really change the title each time from the fragment but in addition i need to disable this line:
getSupportActionBar().setTitle(mDrawerTitle);
from the onDrawerOpened and onDrawerClosed
Do not set the title to ActionBar, set the title to Activity, you can do so from the activity or fragment.
For Activity:
setTitle("New Title");
or for Fragment:
getActivity().setTitle("New Title");
add this in your fragment
getActivity().setTitle("title");
add remove this below line from Drawer activity
getActivity().setTitle("title");
Try this one it worked for me
place a Textview inside the toolbar of app_bar activity
Inside the oncreateView of a fragment put this code
TextView heading;
heading=(TextView)getActivity().findViewById(R.id.Id_title);
heading.setText("your text");
By using this you can Name each fragments with your own text
In onCreateView()write following code:
activity!!.setTitle("Your Text")
If your purpose is "Changing toolbar title according to the fragment name"
i tip to see if the "navigation graph" of the "navigation drawer" you set all stuff correctly: every fragment should have something like this:
<fragment
android:id="#+id/nav_ID_OF_FRAGMENT"
android:name="rubik_cube.navigation.ui.NAME_OF_Fragment"
android:label="#string/TOOLBAR_TITLE_HERE"
tools:layout="#layout/fragment_LAYOUT_GO_HERE" />
and in the resources the fragment desired title string,
in the res/layout the layout of the fragment,
in the code a class that handle the fragment stuff
and toolbar works perfectly!
if u want to change toolbar name dinamically according to other stuff like idk pressing a button, select from menu u need to change it programmatically instead with:
ActionBar toolbar = requireActivity().getSupportActionBar();
if(toolbar != null) toolbar.setTitle("your title");

Button in navigation drawer can't listen click event

I have a relative layout in my navigation drawer, the problem is when
I click a button from navigation drawer I can't get toast. So I think my button not responding.
My layout:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- main screen -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- navigation drawer -->
<RelativeLayout
android:id="#+id/whatYouWantInLeftDrawer"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#android:color/black" >
<Button
android:id="#+id/login"
android:layout_below="#id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:background="#303592"
android:text="Click Me"
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
and here is My full code of deskboard activity:
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import android.app.FragmentManager;
public class DeskboardActivity extends ActionBarActivity {
RelativeLayout leftRL;
RelativeLayout rightRL;
DrawerLayout drawerLayout;
Button first;
String fragment_title;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deskboard);
mTitle = mDrawerTitle = getTitle();
leftRL = (RelativeLayout)findViewById(R.id.whatYouWantInLeftDrawer);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
first = (Button)findViewById(R.id.login);
drawerLayout.setClickable(true);
first.setClickable(true);
first.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//displayView(0);
Toast.makeText(DeskboardActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new UpdatesFragment();
fragment_title = "Updates-BrahmShakti";
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(fragment_title);
drawerLayout.closeDrawer(leftRL);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
public void onOpenLeftDrawer(View view)
{
drawerLayout.openDrawer(leftRL);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.deskboard, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
Toast.makeText(getApplicationContext(), "Toast working", Toast.LENGTH_SHORT).show();
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
EDITED
Isn't it supposed to be
first.setOnClickListener(new View.OnClickListener() { // View.OnClickListener.
#Override
public void onClick(View v) {
Toast.makeText(activity.this, "Clicked", Toast.LENGTH_SHORT).show();
// activityName.this insteade of getApplicationContext.
}
});
<Button
android:id="#+id/login"
android:layout_below="#id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0dip"
android:background="#303592"
android:text="Click Me"
android:textColor="#ffffff"
android:textStyle="bold"
android:onClick="runToast"
/>
first.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runToast(v)
}
});
public void runToast(View v) {
Toast.makeText(activity.this, "Clicked", Toast.LENGTH_SHORT).show();
}

Navigation drawer Error in replace method while replac ing fragments in onclick event

I am trying to implement navigtion drawer this is my code and i am getting error while running the application.
this is the error in problems of eclipse.
Description Resource Path Location Type
The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, Fragment) MainActivity.java /NavigationDrawer/src/com/example/navigationdrawer line 198 Java Problem.
This is my code of main activity
package com.example.testnav;
import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private String[] drawerListViewItems;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
// 2. App Icon
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_launcher, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerLayout.setDrawerListener(actionBarDrawerToggle);
// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
displayView(position);
drawerLayout.closeDrawer(drawerListView);
}
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FragmentOne();
break;
case 1:
fragment = new FragmentTwo();
break;
case 2:
fragment = new FragmentThree();
break;
case 3:
fragment = new FragmentOne();
break;
case 4:
fragment = new FragmentOne();
break;
case 5:
fragment = new FragmentOne();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
//setTitle((TextView)view).getText());
drawerLayout.closeDrawer(drawerListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
and this is fragment
package com.example.testnav;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
public FragmentOne(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
}
this is my xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#666"
android:dividerHeight="1dp"
android:background="#333"
android:paddingLeft="15sp"
android:paddingRight="15sp"
/>
</android.support.v4.widget.DrawerLayout>
Try using FragmentActivity in place of Activity
public class MainActivity extends FragmentActivity
and
default:
fragment = new FragmentOne();
break;
I get the same error. Need to modify tow places, as follows.
First, use FragmentActivity
public class MainActivity extends FragmentActivity
Second, change getFragmentManager to getSupportFragmentManager:
FragmentManager fragmentManager = getSupportFragmentManager();

cant start splash activity before Sherlockfragment Activity

Hi have sherlock fragment activity running which also contain slide menu and i want to have splash screen before this activity and i dont know how to make buttons work in this fragment activity
package com.androidbegin.sidemenututorial;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;
public class MainActivity extends SherlockFragmentActivity {
// Declare Variable
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Main Menu", "Setting",
"About" };
// Generate subtitle
subtitle = new String[] { "", "",
"" };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
R.drawable.collections_cloud };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener for ListView in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment3);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And you have added the Activity to the manifest?

Categories

Resources