doing it the toolbar way instead of list view - java

lvRSS = (ListView)findViewById (R.id.lvRSS)
lvRSS.setOnItemClickListener (new AdapterView.OnItemClickListener(){
public void onItemClick (AdpaterView<?>parent,View view, int position,
long id)
}
it will work on listview but i cant to mimic the same for toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setOnItemClickListener (new AdapterView.OnItemClickListener(){
public void onItemClick (AdpaterView<?>parent,View view, int
position, long id)
}
please help

Toolbar does not contain the setOnItemClickListener () event. If you want to make the event click on Toolbar, try this:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});

Related

Menu-item to show a navigationdrawer and a back arrow to return

I want that the back icon in the toolbar is on the left side and it returns to the previous page. And the menu icon in the toolbar should be on the right side and to show the navigationdrawer.
I already have:
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar=(android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//drawerlayout
mDrawerLayout=(DrawerLayout) findViewById(R.id.activity_main3);
ActionBarDrawerToggle mToggle=new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("NOSTRILS");
Solved the issue by making a lot of changes to code:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private EndDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/* Toolbar */
getSupportActionBar().setTitle("Nostrils");
toolbar.setTitleTextColor(0xFFFFFFFF);
// Back icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initNavigationDrawer();
}
drawerLayout = (DrawerLayout)findViewById(R.id.activity_main3);
drawerToggle = new EndDrawerToggle(this,
drawerLayout,
toolbar,
R.string.open,
R.string.close);
drawerLayout.addDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here.
int id = item.getItemId();
// Back icon clicked
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
finish();
return super.onOptionsItemSelected(item);
}
}

How to extend two Classes on one activity

I'm newbie in this and I'm wondering if I can make my activity to extend two java classes
Why i need that?
In my activity I need a Map and also a Navigation Drawer which will provide all the option where the user will be able to work with.
This is the code from my MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
DrawerLayout drawerLayout;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle("");
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
setSupportActionBar(toolbar);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
I also found out that two classes can't be extended on one activity. Any other solution how can I achieve it.
Тhanks in advance.
In Java, there is no way of extending from two classes
but you can get all the features of that class by creating a new object from that class and use it in your program.
You can also look at this link, it may help you
Update:
I used this method to use Google Maps APIs in my program without Extended class.
public class MapInfoFragment extends Fragment implements OnMapReadyCallback {
private static GoogleMap mMap;
public MapInfoFragment() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_travelling_info, container, false);
SupportMapFragment mMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.frmap);
lnl_map_fragment = rootView.findViewById(R.id.lnl_map_fragment);
mMapFragment.getMapAsync(this);
return rootView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
googleMap.setMapType(1);
googleMap.getUiSettings().setMapToolbarEnabled(false);
googleMap.setIndoorEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.setTrafficEnabled(false);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setRotateGesturesEnabled(false);
googleMap.getUiSettings().setAllGesturesEnabled(false);
googleMap.getUiSettings().setTiltGesturesEnabled(false);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
origin_marker_option.position(origin_ltln)
.title("Origin")
.icon(BitmapDescriptorFactory.fromBitmap(btm_origin))
.flat(false);
googleMap.addMarker(origin_marker_option);
if (ar_dest_lat_lon.size() > 0) {
dest_marker_option_1.position(ar_dest_lat_lon.get(0))
.title("Dest1")
.icon(BitmapDescriptorFactory.fromBitmap(btm_dest_1))
.flat(false);
googleMap.addMarker(dest_marker_option_1);
} else {
builder.include(new LatLng(origin_ltln.latitude - 0.003, origin_ltln.longitude - 0.003));
builder.include(new LatLng(origin_ltln.latitude + 0.003, origin_ltln.longitude + 0.003));
}
builder.include(origin_ltln);
for (LatLng dest_lat_lon : ar_dest_lat_lon)
builder.include(dest_lat_lon);
LatLngBounds bounds = builder.build();
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels / 3;
int padding = (int) (width * 0.12); // offset from edges of the map 12% of screen
int w = lnl_map_fragment.getWidth();
int h = lnl_map_fragment.getHeight();
int p = (int) (w * 0.12);
try {
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, padding));
} catch (Exception e) {
e.printStackTrace();
}
initMapCameraPosition();
}
private void initMapCameraPosition() {
if (mMap == null) return;
}
}
At the request of the respectable questioner, the code was placed
I'm newbie in this and I'm wondering if I can make my activity to extend two java classes.
No, sorry.
In my activity I need a Map and also a Navigation Drawer which will provide all the option where the user will be able to work with
That does not require inheriting from two Java classes.
Assuming that by "Map" you mean the Maps V2 API from the Play Services SDK, you can use a MapFragment for displaying the map.

PreferenceFragment overlaps toolbar in PreferencesActivity

My problem is that my PreferenceFragment overlaps my toolbar. Since I do not have a layout activity which the fragment comes from, I cannot apply the solutions I have seen elsewhere. I got this far by skipping and deleting the pref_header.xml and everything works except the toolbar.
PreferenceActivity.xml
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new GeneralPreferenceFragment())
.commit();
}#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class GeneralPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("bredd"));
bindPreferenceSummaryToValue(findPreference("höjd"));
bindPreferenceSummaryToValue(findPreference("vecka"));
bindPreferenceSummaryToValue(findPreference("klass"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), PreferencesActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Toolbar bar;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
LinearLayout root = (LinearLayout) findViewById(android.R.id.list).getParent().getParent().getParent();
bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false);
root.addView(bar, 0); // insert at top
} else {
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
ListView content = (ListView) root.getChildAt(0);
root.removeAllViews();
bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false);
int height;
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
height = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
} else {
height = bar.getHeight();
}
content.setPadding(0, height, 0, 0);
root.addView(content);
root.addView(bar);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
settings_toolbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:navigationContentDescription="#string/abc_action_bar_up_description"
android:background="?attr/colorPrimary"
app:navigationIcon="?attr/homeAsUpIndicator"
app:title="Settings"
android:elevation="4dp"/>
I am aware of the .replace(R.id.whateverlayoutthefragmentcomesfrom) fix, but since it isn't bound to a layout file, I don't know what to do.
Edit:
Note that getListView().setPadding(0, 50, 0, 0); and similar lines compile, but do not have any practical effect at all.
Edit 2: SOLUTION
Solved by following this thread: link
You have to set the built in "list" of the preferenceFragment/Activity further down with setPadding
Try the following code:
//Put this line in onCreate
getListView().setPadding(0, (int) getTypedValueInDP(50), 0, 0);
private float getTypedValueInDP(float value) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics());
}

Toolbar as action bar in Fragment

In my app, I use NoActionBar style, and I want to add action Bar to the one of my fragment.
In Activity I can do this like:
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
How do this in fragment ?
I tried so:
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);
return inflater.inflate(R.layout.fragment_training, container, false);
}
But it doesn't work.
UPD
I think the problem in this line:
Toolbar actionBar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(actionBar);
Old question)), should be:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.my_app_bar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//return inflater.inflate(R.layout.fragment_training, container, false);
View v = inflater.inflate(r.layout.fragment_training, container, false);
Toolbar toolbar = (Toolbar) v.findviewbyid(r.id.my_app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
return v;
}
May be you need to,
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle();
These 2 links will be helpful for you,
Set up toolbar as actionbar in fragment
How to get Toolbar from fragment?
Hope this helps.

How recreate or refresh fragment

i have fragment for display the NavigationDrawer. In that i have the first section the header with some information. This information change and with EventBus i control this event, but how can update this fragment?
The implementation below work only if i rotate the device.
extract from MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
mNavigationNavDrawerFragment = (Nav_DrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationNavDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
inizialized(mServices);
}
....
....
EventBus.getDefault().postSticky(new PersonDetails(mNomeCognome, mEmail));
//HERE HOW CAN REFRESH OR RECREATE THIS mNavigationNavDrawerFragment?
}
Extract from Nav_DrawerFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
//HERE I SET THE UPDATE DATA
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition,items);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().registerSticky(this);
}
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu();
}
};
I can see you're using a RecyclerView with the adapter
Nav_adapter adapter = new Nav_adapter(navigationItems,mNomeCognome,mEmail);
and then you're updating the values that were used to create the adapter on the event
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
the problem is that you didn't pass those values to the adapter.
So you'll have to create a way to pass those updated values to the existing adapter, something like this:
// first define your adapter as a field:
Nav_adapter adapter;
// then on your event
public void onEventMainThread(PersonDetails event){
mNomeCognome = event.mNomeCognome;
mEmail = event.mEmail;
adapter.setNewValues(mNomeCognome, mEmail);
}
then inside this setNewValues you update the adapter values and don't forget to call one of the notifyItemChanged or notifyItemRangeChanged method on the adapter so that the new value can be updated on the screen.

Categories

Resources