How to inflate badge counter in MenuItem using custom LayerDrawable - android

I was following this article. Unfortunatelly, badge isn't drawn. Of course I changed invalidateOptionsMenu method to supportInvalidateOptionsMenu method.
I was checking the log, step by step and found out that draw method in custom Drawable named BadgeDrawable is never called. Why is that?
I'm trying to use it in AppCompatActivity using Support Design Library version 23.0.1
I saw this answer but it seems to be out of date.
Is there anyone who managed to implement badger counter for MenuItem icon inside android.support.v7.widget.Toolbar?
If the way shown in the article is wrong then could you suggest other way to achieve the result as in example below?:
Here is a setup inside my application:
LayerDrawable XML ic_filter_notifications.xml:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/ic_filter_notification"
android:drawable="#drawable/ic_filter_grey600_18dp"
android:gravity="center"/>
<!-- set a place holder Drawable so android:drawable isn't null -->
<item android:id="#+id/ic_filter_badge"
android:drawable="#drawable/ic_filter_grey600_18dp">
</item>
</layer-list>
Menu that I use in the Toolbar menu_activity_main.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cobytu="http://schemas.android.com/apk/res-auto" >
<item
android:id="#+id/menu_settings"
android:orderInCategory="100"
android:title="#string/menu_settings"
cobytu:showAsAction="never"/>
<item
android:id="#+id/menu_logout"
android:orderInCategory="1000000"
android:title="#string/menu_logout"
cobytu:showAsAction="never"/>
<item
android:id="#+id/action_filter"
android:title="#string/filters"
android:icon="#drawable/ic_filter_notifications"
cobytu:showAsAction="always"/>
<item
android:id="#+id/action_location"
android:icon="#drawable/ic_map_marker_radius_grey600_18dp"
android:title="#string/location"
cobytu:showAsAction="always"/>
</menu>
This is function sets the count int for new BadgeDrawable inside UsefulFunctions class - UsefulFunctions.java:
public class UsefulFunctions {
private Context ctx;
public UsefulFunctions(Context context){
ctx = context;
}
public static void setBadgeCount(Context context, LayerDrawable icon,
int count) {
BadgeDrawable badge;
// Reuse drawable if possible
Drawable reuse = icon.findDrawableByLayerId(R.id.ic_filter_badge);
if (reuse != null && reuse instanceof BadgeDrawable) {
badge = (BadgeDrawable) reuse;
} else {
Log.d("mTAG", UsefulFunctions.class.getName()
+ " I'm creating new BadgeDrawable!");
badge = new BadgeDrawable(context);
}
badge.setCount(count);
icon.mutate();
Log.d("mTAG",
UsefulFunctions.class.getName() + " badge: " + badge.toString()
+ " count: " + count);
icon.setDrawableByLayerId(R.id.ic_filter_badge, badge);
}
}
This is the important scrap of my MainActivity where I invoke BadgeDrawable creation. I also show what's inside onCreate and in onOptionsItemSelected, may be needed - MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DialogFragmentFilters.FiltersRefreshInterface{
public String username;
//CollapsingToolbarLayout
private CollapsingToolbarLayout mCollapsingToolbarLayout;
//Toolbar
private Toolbar mToolbar;
//TabLayout
private TabLayout mTabLayout;
private ViewPager mPager;
private MyPagerAdapter mAdapter;
//NavigationDraver
private static final String SELECTED_ITEM_ID = "selected_item_id";
private static final String FIRST_TIME = "first_time";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private NavigationView mNavigationView;
private int mSelectedId;
private boolean mUserSawDrawer = false;
private TextView mNavHeaderNameText;
private TextView mNavHeaderEmailText;
private DatabaseHandler db;
private UserFunctions userFunctions;
private AlertDialog.Builder dialogBuilder;
private AlertDialog alertDialog;
private JSONObject jsonLocation = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFunctions = new UserFunctions();
db = new DatabaseHandler(getApplicationContext());
username = db.getUserDetails().get(DatabaseHandler.getKEY_USER_LOGIN());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
setupToolbar();
setupTablayout();
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
View header = LayoutInflater.from(MainActivity.this).inflate(R.layout.nav_header, null);
mNavHeaderNameText = (TextView) header.findViewById(R.id.tv_nav_header_name);
mNavHeaderNameText.setText("Siema "+username+"!");
mNavHeaderEmailText = (TextView) header.findViewById(R.id.tv_nav_header_email);
mNavHeaderEmailText.setText(db.getUserDetails().get(DatabaseHandler.getKEY_USER_EMAIL()));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
if (!didUserSeeDrawer()) {
showDrawer();
markDrawerSeen();
} else {
hideDrawer();
}
mSelectedId = savedInstanceState == null ? R.id.navigation_item_4 : savedInstanceState.getInt(SELECTED_ITEM_ID);
navigate(mSelectedId);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(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();
showActionDialog(id);
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.menu_settings:
return true;
case R.id.menu_logout:
dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(
MainActivity.this, R.style.Theme_AppCompat_Light_Dialog));
dialogBuilder
.setTitle(getResources().getString(R.string.logoutAlertTitle))
.setIcon(R.drawable.ic_logout).setMessage(getResources().getString(R.string.logoutAlertMessage)).setPositiveButton(getResources().getString(R.string.logoutAlertYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
((RelativeLayout) findViewById(R.id.fl_mainContent))
.animate()
.alpha(0f)
.setListener(
new AnimatorListenerAdapter() {
public void onAnimationEnd(
Animator animation) {
mDrawerLayout
.setVisibility(View.INVISIBLE);
mDrawerLayout
.setAlpha(1f);
mDrawerLayout
.animate()
.setListener(null);
}
});
userFunctions.logoutUser(getApplicationContext());
Intent i = new Intent(MainActivity.this, LoginActivity.class);
// MainActivity.this.deleteDatabase("cobytu_db");
startActivity(i);
finish();
}
})
.setNegativeButton(getResources().getString(R.string.logoutAlertNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog = dialogBuilder.create();
alertDialog.show();
return true;
}
return false;
}
public int filterCounter = 0;
class FetchCountTask extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
// example count. This is where you'd
// query your data store for the actual count.
return 5;
}
#Override
public void onPostExecute(Integer count) {
setNotifCount(count);
}
}
private void setNotifCount(int count){
filterCounter = count;
supportInvalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main, menu);
MenuItem item = menu.findItem(R.id.action_filter);
LayerDrawable icon = (LayerDrawable) item.getIcon();
// Update LayerDrawable's BadgeDrawable
Log.d("mTag", "onCreateOptionsMenu: this: " + this.toString());
UsefulFunctions.setBadgeCount(this, icon, filterCounter);
return true;
}
#Override
public void onRefreshFilters(int counter) {
setupTablayout();
Toast.makeText(MainActivity.this, "List has been refreshed! " + counter, Toast.LENGTH_SHORT).show();
filterCounter = counter;
new FetchCountTask.execute();
}
}

Related

how to add Activity class in DrawerLayout in android?

I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/

How to highlight the imagebutton when it is pressed

I want my imagebutton to hightlight it self, as the normal glow effect when a "normal" button is pressed. So i tried to put the image in, but then there is a "gray field" in the back of the image so i made it transparent so only the image will show but then the glow effect disappeared. Is there a solution to this? :)
please see imgur image as a example- Example image here
if it is to "hard" I can live with the gray field behind the image but is it possible then to make it green with the same highlight effect?
Should i put the code in MainActivity or my fragment java?
Fragment java
public class FirstFragment extends Fragment {
private View view ;
public FirstFragment(){
}
Button sendSMS;
Button sendSMSaon;
Button sendSMSaoff;
Button sendSMSrela1;
Button sendSMSrela2;
EditText msgTxt;
EditText aonTxt;
EditText aoffTxt;
EditText rela1txt;
EditText rela2txt;
Button taframnummer;
TextView nyanumtxt;
//TextView nya;
//TextView nsp;
TextView tstnr;
#SuppressWarnings("ResourceType")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.first_layout, container, false);
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
view = getActivity().findViewById(R.id.content_frame);
nyanumtxt = (TextView) getActivity().findViewById(R.id.raderanumtxt);
sendSMS = (Button)view.findViewById(R.id.skicka);
sendSMSaon = (Button)view.findViewById(R.id.skickaaon);
sendSMSaoff = (Button)view.findViewById(R.id.skickaaoff);
sendSMSrela1 = (Button)view.findViewById(R.id.skickarela1);
sendSMSrela2 = (Button)view.findViewById(R.id.skickarela2);
msgTxt = (EditText)view.findViewById(R.id.Textmeddelande);
aonTxt = (EditText)view.findViewById(R.id.aon);
aoffTxt = (EditText)view.findViewById(R.id.aoff);
rela1txt = (EditText)view.findViewById(R.id.rela1txt);
rela2txt = (EditText)view.findViewById(R.id.relä2txt);
taframnummer = (Button) view.findViewById(R.id.taframnummer);
//nsp = (TextView) view.findViewById(R.id.nummertestsp);
// tstnr = (TextView) view.findViewById(R.id.numretladd);
// view = getActivity().findViewById(R.id.content_frame);
taframnummer.setVisibility(INVISIBLE);
msgTxt.setVisibility(INVISIBLE);
aonTxt.setVisibility(INVISIBLE);
aoffTxt.setVisibility(INVISIBLE);
rela1txt.setVisibility(INVISIBLE);
rela2txt.setVisibility(INVISIBLE);
sendSMSaoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaoff = aoffTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaoff);
}
}
);
sendSMSaon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgaon = aonTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgaon);
}
}
);
sendSMS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsg = msgTxt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsg);
}
}
);
sendSMSrela1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String myMsgrela1 = rela1txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, myMsgrela1);
}
}
);
sendSMSrela2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String mymsgrela2 = rela2txt.getText().toString();
String theNumberr = nyanumtxt.getText().toString();
sendMsg(theNumberr, mymsgrela2);
}
}
);
// return view;
}
private void sendMsg(String theNumber, String myMsg)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(theNumber, null, myMsg, null, null);
}
}
Here my MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//TextView tstnr;
TextView radertst;
Button sendSMSaon;
EditText aonTxt;
//TextView nrladd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// tstnr = (TextView) findViewById(R.id.nummertestsp);
radertst = (TextView) findViewById(R.id.raderanumtxt);
sendSMSaon = (Button)findViewById(R.id.skickaaon);
aonTxt = (EditText)findViewById(R.id.aon);
// nrladd = (TextView)findViewById(R.id.numretladd);
}
//This is where the call for the value in the setttings are.
//Här är så att man kan lägga in values från inställningar till mainactivity.
public void displayData(View view){
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");
}
//downbelow is where the onresume so the value boots up with the app.
//nedanför är för att appen ska ladda koden i settings direkt när man startar
#Override
protected void onResume() {
super.onResume();
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(this);
String name = prefs.getString("example_text", "");
radertst.setText(name + " ");}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_first_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
// Handle the camera action
} else if (id == R.id.nav_second_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new SecondFragment())
.commit();
} else if (id == R.id.nav_third_layout) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ThirdFragment())
.commit();
}
else if (id == R.id.nav_share) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://hellmertz.se"));
startActivity(browserIntent);
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Put the imageView that you want to highlight above a View with bright color and set the visibility of the view equal to View.GONE. Now with your ImageButton
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
myView.setVisibility(View.VISIBLE);
break;
}
case MotionEvent.ACTION_UP:
myView.setVisibility(View.GONE);
break;
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
myView.setVisibility(View.GONE);
break;
}
}
return true;
}
});
You can user selector drawable and have 3 different button drawables for each state. Create these file is drawables folder and add this line to button android:background="#drawable/button_selector"
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed -->
<item android:drawable="#drawable/camera_button_hold" android:state_pressed="true"/>
<!-- focused -->
<item android:drawable="#drawable/camera_button_hold" android:state_focused="true"/>
<!-- default -->
<item android:drawable="#drawable/camera_button_normal"/>
</selector>
camera_button_hold.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="#673ab7"/>
</shape>
camera_button_normal.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="#673ab7"/>
</shape>

why my splash screen is so long

I'm trying to implement a splash screen on my app. After the loading of the splash screen, I have two issues.
If the user is connected, an activity is started. If not, an other is started.
But, with my implementation, when the user is connected, the splash screen is very long (8 or 9 sec), but I don't know why.
That is my first class which check if the user is connected, and it load some shared preferences? So maybe it's that?
public class AnnaActivity extends AppCompatActivity {
public PrefManager pref;
private AllRequest req;
private static final String REQUEST_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.pref = new PrefManager(getApplicationContext());
boolean isco = pref.getIsConnect();
if (isco) {
Log.e("SPLASH", "IsConnected");
Intent loginActivity = new Intent(this, NavigationDrawerActivity.class);
startActivity(loginActivity);
finish();
} else {
Log.e("SPLASH", "launch login activity");
Intent loginActivity = new Intent(this, MainActivity.class);
startActivity(loginActivity);
finish();
}
}
}
that is my splash drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/colorPrimaryDark"/>
<item android:bottom="8dp"
android:top="8dp"
android:left="8dp"
android:right="8dp">
<bitmap android:gravity="center"
android:src="#mipmap/ic_launcher"
android:antialias="true"/>
</item>
</layer-list>
And my splach style
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_drawable</item>
</style>
(Edit post) The navigation drawerActivity
public class NavigationDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Response.Listener, Response.ErrorListener{
public TextView TextViewEmailAddress;
public TextView TextViewLogin;
private PrefManager pref;
private AllRequest req;
public RequestQueue mQueue;
private static final String REQUEST_TAG = "LogOutActivity";
private String address;
private String login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
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();
// }
// });
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
this.TextViewEmailAddress = (TextView)header.findViewById(R.id.textView_drawer_mail);
this.TextViewLogin = (TextView)header.findViewById(R.id.textView_drawer_login);
this.pref = new PrefManager(getApplicationContext());
this.req = new AllRequest(getApplicationContext());
this.mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
address = this.pref.getEmail();
login = this.pref.getLogin();
this.TextViewEmailAddress.setText(address);
this.TextViewLogin.setText(getText(R.string.text_view_login_drawer) + " " + login);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_drawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_mon_compte) {
Intent intent = new Intent(NavigationDrawerActivity.this, MyAccountActivity.class);
startActivity(intent);
} else if (id == R.id.nav_deconnection) {
deconnexion();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void deconnexion(){
LayoutInflater factory = LayoutInflater.from(this);
final View alertDialogView = factory.inflate(R.layout.alertdialog_logout, null);
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(alertDialogView);
adb.setTitle(R.string.alertDialod_logout_Title);
adb.setPositiveButton((R.string.alertDialog_logout_PositiveBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String accessToken = pref.getAccessToken();
req.revokeTokenRequest(REQUEST_TAG, accessToken, NavigationDrawerActivity.this, NavigationDrawerActivity.this);
pref.logout();
Intent intent = new Intent(NavigationDrawerActivity.this, MainActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton((R.string.alertDialog_logout_NegativeBtnName), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
adb.show();
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("errrrrrror :(", "it's not working");
}
#Override
public void onResponse(Object response) {
Log.e("pololololo","it's working :D");
}
}

Android restore listview content

I have got two activities. In first you can input jobname and job place into inputtext views. First activity contains also navigation-draver menu (appearing from left side of screen). After clicking "Searc" button, results are shown in listview in second activity. You can long-click on any listview item and then it will be added to navigation-drawer in first activity. You can go back to first activity by clicking "back" arrow. The problem is, that when I will go back to first activity, press "Search" button again and then go back to first activity again, the navigation drawer menu is empty again (all items, which were added on first try are deleted). How to fix that?
Here is pic with my activities (sorry for poor quality):
1- first activity; 2- navigation drawer in first activity with added items from second activity' listview; 3- second activity (listview with search results)
EDIT:
My code from two activities (without imports to shorten it a little):
First (main):
public class MainActivity extends ActionBarActivity {
ListviewActivity lv = new ListviewActivity();
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
public ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ArrayList<String> arrayFav = new ArrayList<String>();
ArrayList<String> arrayLin = new ArrayList<String>();
private ImageView mImageViewLogo;
private Button mButtonSzukaj;
private EditText mEditTextPraca;
private EditText mEditTextMiejsce;
public static String nazwaStanowiska;
public static String nazwaMiejscowosci;
private Settings mSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mImageViewLogo = (ImageView)findViewById(R.id.imageViewLogo);
mButtonSzukaj = (Button) findViewById(R.id.buttonSzukaj);
mEditTextPraca = (EditText)findViewById(R.id.editTextPraca);
mEditTextMiejsce = (EditText)findViewById(R.id.editTextMiejsce);
final String mPrBefore = mEditTextPraca.getText().toString();
final String mPrAfter = mPrBefore.trim();
final String mMiBefore = mEditTextMiejsce.getText().toString();
final String mMiAfter = mMiBefore.trim();
mEditTextPraca.setText(mPrAfter);
mEditTextMiejsce.setText(mMiAfter);
mSettings = new Settings(this);
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
mDrawerList.setOnItemClickListener(null);
mDrawerList.setOnItemLongClickListener(null);
}
mAdapter.notifyDataSetChanged();
mButtonSzukaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(mEditTextPraca.getText().toString()) && (TextUtils.isEmpty(mEditTextMiejsce.getText().toString()))) {
mEditTextPraca.setError("Pole obowiązkowe!");
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextPraca.getText().toString())) {
mEditTextPraca.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextMiejsce.getText().toString())) {
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else {
nazwaStanowiska = mEditTextPraca.getText().toString();
nazwaMiejscowosci = mEditTextMiejsce.getText().toString();
Intent myIntent = new Intent(MainActivity.this, ListviewActivity.class);
MainActivity.this.startActivityForResult(myIntent, 1);
mSettings.setmText1(mEditTextPraca.getText().toString());
mSettings.setmText2(mEditTextMiejsce.getText().toString());
mSettings.save();
}
}
});
readPreferences();
}
protected void readPreferences(){
mEditTextPraca.setText(mSettings.getmText1());
mEditTextMiejsce.setText(mSettings.getmText2());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
ArrayList<String> passedText = data.getStringArrayListExtra("text");
ArrayList<String> passedLink = data.getStringArrayListExtra("link");
//arrayFav.clear();
//arrayLin.clear();
arrayFav.addAll(passedText);
arrayLin.addAll(passedLink);
addDrawerItems();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.podziel_sie_opinia) {
Intent mIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:661249888"));
mIntent.putExtra("sms_body", "Uważam, że aplikacja...");
startActivity(mIntent);
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void addDrawerItems() {
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayFav);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Tu pojawi się kliknięta oferta", Toast.LENGTH_LONG).show();
/*Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onet.pl"));
startActivity(myBrowserIntent);*/
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(arrayLin.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Usunięto z ulubionych!", Toast.LENGTH_SHORT).show();
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
}
mAdapter.notifyDataSetChanged();
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Twoje oferty");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
protected void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
and the second one (listview with results):
public class ListviewActivity extends ActionBarActivity {
int global_position =0;
boolean longClick = false;
static String wybranaOferta = "";
ArrayList<String> choosedOffer = new ArrayList<String>();
ArrayList<String> choosedLink = new ArrayList<String>();
MainActivity mainActiv;
static List<String> mLista = new ArrayList<>();
static ArrayList<String> positionArr = new ArrayList<String>();
static List<String> mListaTest1 = new ArrayList<>();
static List<String> mListaTest2 = new ArrayList<>();
static List<String> mListaLinki = new ArrayList<>();
static List<String> mListaNazwy = new ArrayList<>();
static List<String> mListaFirmy = new ArrayList<>();
private JobListAdapter mAdapter;
public Elements jobName, jobName2, jobNameComp, jobName2Comp;
private ProgressBar mProgress;
private Context context;
public ArrayList<String> workList = new ArrayList<String>();
public ArrayList<String> companyList = new ArrayList<String>();
public ArrayList<String> jobList = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private JazzyListView mListView;
public String doURLpraca = MainActivity.nazwaStanowiska;
public String doURLmiejsce = MainActivity.nazwaMiejscowosci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListView = (JazzyListView) findViewById(R.id.list);
mListView.setTransitionEffect(new FanEffect());
mListView.setItemsCanFocus(true);
//Progress bar
mListView.setEmptyView(findViewById(R.id.progressBarLoading));
Toast.makeText(getApplicationContext(), "Wyszukiwanie ofert...", Toast.LENGTH_LONG).show();
new NewThread().execute();
mAdapter = new JobListAdapter(this, jobList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mListaLinki.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
choosedOffer.add(mListaTest1.get(position).toString());
choosedLink.add(mListaLinki.get(position).toString());
Toast.makeText(getApplicationContext(), "Dodano do ulubionych!", Toast.LENGTH_SHORT).show();
return false;
}
});
}
protected void onPreExecute() {
}
public void onBackPressed() {
Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
intent.putStringArrayListExtra("text", choosedOffer);
intent.putStringArrayListExtra("link", choosedLink);
setResult(RESULT_OK, intent);
finish();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
String doURLwork = mainActiv.nazwaStanowiska;
String doURLplace = mainActiv.nazwaMiejscowosci;
Document doc, doc2;
Elements classs, lins;
String uerele;
try {
doc = (Document) Jsoup.connect("http://www.infopraca.pl/praca?q=" + doURLwork + "&lc=" + doURLplace)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
doc2 = (Document) Jsoup.connect("http://www.pracuj.pl/praca/" + doURLwork + ";kw/" + doURLplace + ";wp")
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
//Oferty
jobName = doc.select("h2.p-job-title a[href]"); //Infopraca
jobName2 = doc2.select("h2.offer__list_item_link a[href]"); //pracuj.pl
//Firmy
jobNameComp = doc.select("h3.p-name.company a[href]"); //Infopraca
jobName2Comp = doc2.select("h3.offer__list_item_link a[href]"); //pracuj.pl
//Oferty pracy
//Infopraca
mListaTest1.clear();
for (Element jobNames : jobName) {
mListaTest1.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2) {
mListaTest1.add(jobNames2.text() + "\n");
}
if(mListaTest1.size()==0){
Toast.makeText(getApplicationContext(), "Zmień parametry wyszukiwania!", Toast.LENGTH_LONG).show();
}
//--------------------------------------------------
//Firmy
//Infopraca
mListaTest2.clear();
for (Element jobNames : jobNameComp) {
mListaTest2.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2Comp) {
mListaTest2.add(jobNames2.text() + "\n");
}
//Linki do ofert
//Infopraca
for (Element link : jobName) {
mListaLinki.add(link.attr("abs:href"));
}
//Pracuj.pl
for (Element link : jobName2) {
mListaLinki.add(link.attr("abs:href"));
}
//Łączenie wyników - oferta + nazwa firmy
jobList.clear();
for(int i=0; i<mListaTest1.size(); i++){
jobList.add(mListaTest1.get(i)+"\n"+mListaTest2.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute(String result) {
}
#Override
protected void onPostExecute(String result) {
mAdapter.notifyDataSetChanged();
}
}
}
Generally, the first activity may be destroyed and recreated each time you go back to it. You might have to save list view items in activity's
onSaveInstanceState(Bundle)
method and load them again in onCreate. A simple example can be found in the first answer here
Or, you can just use fragments instead of two activities.
EDIT:
It seems like onSaveInstanceState only works when the activity is being closed by force, and it's philosophy is that onDestroy() method is not a safe place to save your data since it might not get called for various reasons.
The easiest way to do this is to use fragments instead of separate activities. The list adapter should be a member of activity and instead of opening a new activity, a fragment transaction would take place.
Using the back stack of fragment manager, the back button navigation will also be no problem and it would return the app to its initial state. Since the list is a field of the activity it can be easily shared between the fragments and it would not change due to fragment transactions.

android-navigation drawer not open on activity change

it's weird , I spend last 5 hours on it , nothing worked. the problem is this ,When I go from activity a to activity b , and press back button and come back to activity a, the navigation drawer not open.
this is the code :
public abstract class DrawerActivity extends ActionBarActivity {
static LinearLayout fullLayout;
static FrameLayout actContent;
static DrawerLayout mDrawerLayout;
static ListView mDrawerList;
static ActionBarDrawerToggle mDrawerToggle;
static LinearLayout mDrawer;
List<HashMap<String, String>> mList;
SimpleAdapter mAdapter;
final private String COUNTRY = "country";
final private String FLAG = "flag";
final private String COUNT = "count";
#Override
public void setContentView(final int layoutResID) {
fullLayout= (LinearLayout) getLayoutInflater().inflate(R.layout.act_layout, null); // Your base layout here
actContent= (FrameLayout) fullLayout.findViewById(R.id.act_content);
getLayoutInflater().inflate(layoutResID, actContent, true); // Setting the content of layout your provided to the act_content frame
super.setContentView(fullLayout);
makelist();
}
mTitle = (String) getTitle();
// Getting a reference to the drawer listview
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting a reference to the sidebar drawer ( Title + ListView )
mDrawer = (LinearLayout) findViewById(R.id.drawer);
// Each row in the list stores country name, count and flag
mList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < mCountries.length; i++) {
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(COUNTRY, mCountries[i]);
hm.put(FLAG, Integer.toString(mFlags[i]));
mList.add(hm);
}
String[] from = { FLAG, COUNTRY };
int[] to = { R.id.flag, R.id.country };
mAdapter = new SimpleAdapter(this, mList, R.layout.drawer_layout, from,to);
// Getting reference to DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_navigation_drawer, R.string.drawer_open,R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
highlightSelectedCountry();
supportInvalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
supportInvalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
Log.v("this","close");
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
// Setting event listener for the drawer
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setAdapter(mAdapter);
}
public static boolean open() {
if (mDrawerLayout.isDrawerOpen(mDrawer)) {
mDrawerLayout.closeDrawer(Gravity.RIGHT);
return true;
} else {
mDrawerLayout.openDrawer(Gravity.RIGHT);
return true;
}
}
this is MainActivity class:
public class MainActivity extends DrawerActivity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//suppose this is the imageview on the actionbar
ImageView img=(ImageView)dialogg.findViewById(R.id.img);
dateup.img(new OnClickListener() {
#Override
public void onClick(View v) {
DrawerActivity.open();
}
});
}
one thing I want to notice , the mainActivity extends DrawerActivity class.
Could you help me to solve this ?
thanks you
This
trys to use the method open() from the Abstract class and you use "mDrawerLayout" and this must be null at this moment i think
public void onClick(View v) {
DrawerActivity.open();
}
maybe you use
public void onClick(View v) {
this.open();
}
Then you will use the open-Method of your current Activity
And you have to implement the onClickListener in the Activity
An error msg would be nice to get more information about the error

Categories

Resources