Hide a Floating Action Button of another Layout - java

I have a FloatingActionButton inside of may activity_main.xml layout which is named fabBtn.
My application is built with a ViewPager and three Fragments.I want to hide the FloatingActionButton when my first Fragment detects a scroll, but I keep getting a NullPointerException if the user starts scrolling.
I believe it could be that my fragment can't get the FloatingActionButton from the activity_main.xml layout?
Here is my activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lh.com.newme.MainActivity"
xmlns:fab="http://schemas.android.com/tools">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|snap"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabMode="fixed"
app:layout_scrollFlags="snap|enterAlways"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#ffffff" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabBtn"
android:layout_marginBottom="#dimen/codelab_fab_margin_bottom"
android:layout_marginRight="#dimen/codelab_fab_margin_right"
android:layout_width="wrap_content"
fab:fab_type="normal"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
app:backgroundTint="#color/fab_ripple_color"
android:src="#drawable/ic_plus"
app:fabSize="normal"
/>
</android.support.design.widget.CoordinatorLayout>
Here is my first Fragment from where I want to hide the FloatingActionButton:
public class Ernaehrung extends Fragment {
NestedScrollView nsv;
FloatingActionButton fab;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
final View rootView = inflater.inflate(R.layout.ernaehrung, container, false);
Button Fruehstuck = (Button) rootView.findViewById(R.id.fruehstuck);
Button Mittagessen = (Button) rootView.findViewById(R.id.mittagessen);
Button Snacks = (Button) rootView.findViewById(R.id.snacks);
Fruehstuck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent FruehstuckScreen = new Intent(getActivity(), lh.com.newme.Fruehstuck.class);
startActivity(FruehstuckScreen);
}
});
Mittagessen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent MittagScreen = new Intent(getActivity(), lh.com.newme.Mittagessen.class);
startActivity(MittagScreen);
}
});
Snacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SnackScreen = new Intent(getActivity(), lh.com.newme.Snacks.class);
startActivity(SnackScreen);
}
});
nsv = (NestedScrollView)rootView.findViewById(R.id.Nsv);
fab = (FloatingActionButton)rootView.findViewById(R.id.fabBtn);
nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (oldScrollY < scrollY){
fab.hide();
}
else
fab.show();}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.main_menu_ernaehrung, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
int id = item.getItemId();
if (id == R.id.benutzer){
}
return super.onOptionsItemSelected(item);
}
}
This is my MainActivity.class :
public class MainActivity extends AppCompatActivity {
FloatingActionButton fabBtn;
CoordinatorLayout rootLayout;
Toolbar toolbar;
TabLayout tabLayout;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.show();
...
break;
case 1:
fab.show();
...
break;
case 2:
fab.hide();
break;
default:
fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
initInstances();
}
private void initInstances() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
rootLayout = (CoordinatorLayout) findViewById(R.id.rootLayout);
fabBtn = (FloatingActionButton) findViewById(R.id.fabBtn);
}
#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_edit, 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.einstellungen) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

First of all, change your line
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
to
fabBtn = (FloatingActionButton)findViewById(R.id.fabBtn);
Solution #1 - get view (if you need object)
Then, in your MainActivity add getter for your FloatingActionButton, like
public FloatingActionButton getFloatingActionButton {
return fabBtn;
}
Finally, in your Fragment call:
FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();
and
if (floatingActionButton != null) {
floatingActionButton.hide();
}
or
if (floatingActionButton != null) {
floatingActionButton.show();
}
Solution #2 - add two methods in MainActivity (if you need only specific methods, like show() / hide())
public void showFloatingActionButton() {
fabBtn.show();
};
public void hideFloatingActionButton() {
fabBtn.hide();
};
And in your Fragment call to hide:
((MainActivity) getActivity()).hideFloatingActionButton();
or to show:
((MainActivity) getActivity()).showFloatingActionButton();
Note
If you use more than one Activity, you must check if it's proper Activity:
if (getActivity() instanceof MainActivity) {
getActivity().yourMethod(); // your method here
}

In your fragment your rootView layout is not main layout and you cannot expect the rootView will return the fab button. Thats why you are getting null pointer exception
You better use interface to detect page scrolling and controll it via your activity

Related

Recyclerview in fragment not displaying alert dialog result right away

In my project I have a main activity with 3 fragments that are displayed via a ViewPager in a TabLayout on launch. In one of my fragments I have a RecyclerView and a FAB that, when clicked, launches an alert dialog that captures user input to be displayed in the RV in the fragment. Upon clicking ADD in the dialog, nothing appears in the RV but when I click the FAB and try again, it appears in the RV. So what I am saying, I have to input info in the FAB twice before it displays in my RV in my fragment. So I was wondering if someone could help me understand why this is happening. It seems like my RV in my frag is not being created right away, but all in all my app is not crashing so I have no log to post. I've research but to no avail. I am self taught so any help would be appreciated.
Fragment
public class SubjectsFrag extends DialogFragment implements CardAdapter.ClickListener,
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public CardAdapter cardAdapter;
public SubjectsModel model = null;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper dbHelper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
cardAdapter = new CardAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cardAdapter);
return view;
}
#Override
public void itemClicked(View view, int position) {
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel(sTitle, sTeacher);
model.setmTitle(title);
model.setmTeacher(teacher);
subMod.add(model);
cardAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Dialog Fragment
public class SubjectsEditor extends DialogFragment
{
Context context;
private OnAddSubjectListener listener;
#BindView(R.id.main_root)
ViewGroup root;
public interface OnAddSubjectListener
{
void OnAddSubjectSubmit(String title, String teacher);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try{
listener = (OnAddSubjectListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement onAddSubjectListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.editor_subjects, container, false);
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate(R.layout.editor_subjects, root);
final EditText mTitle = view.findViewById(R.id.edit_subject);
final EditText mTeacher = view.findViewById(R.id.edit_subject_teacher);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Add Subject")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sTitle = mTitle.getText().toString();
final String sTeacher = mTeacher.getText().toString();
listener.OnAddSubjectSubmit(sTitle, sTeacher);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Recycler Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>
{
public ArrayList<SubjectsModel> subMod;
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
public CardAdapter(Context context, ArrayList<SubjectsModel> items)
{
this.context = context;
this.subMod = items;
}
#NonNull
#Override
public CardAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
return new CardViewHolder(LayoutInflater.from(context).inflate(R.layout.subjects_item_list,
parent, false));
}
#Override
public void onBindViewHolder(final CardAdapter.CardViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
}
public class CardViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public CardViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
clickListener.itemClicked(view, getAdapterPosition());
Toast.makeText(context, R.string.hello_blank_fragment, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public int getItemCount()
{
return subMod.size();
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
CardAdapter.clickListener = clicked;
}
public interface ClickListener
{
public void itemClicked(View view, int position);
}
}
Fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
Main Activity
public class OverviewActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
CharSequence tabTitles[] = {"SUBJECTS", "TASKS", "CALENDER"};
int numOfTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_nav);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), tabTitles, numOfTabs);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
setupDrawerContent(mNavigationView);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed()
{
//DrawerLayout drawer = 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_nav, 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);
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.nav_grades:
Intent gradesIntent = new Intent(this, GradesActivity.class);
startActivity(gradesIntent);
break;
case R.id.nav_notes:
Intent notesIntent = new Intent(this, NotesActivity.class);
startActivity(notesIntent);
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawer.closeDrawer(GravityCompat.START);
}
}
Using notifyDataSetChanged() should do the trick. Check this answer
Giving it a once-over, nothing jumped out. You can use either the debugger or Log.d(String, String) calls to challenge your assumptions about what’s being called when. I’d take a closer look at when you call your adapter’s notifyDataSetChanged() and then at the getItemCount and bind or createViewHolder calls inside the adapter itself.

How to add selected players from MyPlayerActivity and add those players into MainActivity Map as markers?

I would like to select few players ( highlighted in purple colors ie Player 1, Player 3 & Player 5) from 'MyPlayerActivity' and add these selected players into a mapbox Map as markers (MainActivity) during on click on 'Add Player' button.
Could someone please help me on how to achieve this ?
Following is my 'MyPlayerActivity' code
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" + players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#+id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="#+id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="#string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(#NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
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("Navigation!");
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
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("\nTelemetryService is not configured in your applications AndroidManifest.xml. " +
"\nPlease add \"com.mapbox.mapboxsdk.telemetry.TelemetryService\" service in your applications AndroidManifest.xml" +
"\nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
To add a marker to the map you can use this snippet:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
If the listview and map are in separate activities, you can pass the selected player information to the map activity using an intent. Is this what you were looking for?

Pull refresh with recycle view doesn't work

When I move the screen of my device under to refresh rss news feed, it doesn't work. i tried to refresh news with swiperefreshlayout. I don't know why but it doesn't work:
MAIN ACTIVITY:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
SwipeRefreshLayout refreshLayout;
private LinearLayoutManager linearLayoutManager;
private MyAdapter myRecyclerViewAdapter;
Context context;
ArrayList<FeedItem> feedItems=new ArrayList<FeedItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
refreshLayout=(SwipeRefreshLayout)findViewById(R.id.swipeLayout);
refreshLayout.setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) context);
refreshLayout.setColorSchemeColors(0, 0, 0, 0);
refreshLayout.setProgressBackgroundColor(android.R.color.transparent);
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();
}
});
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
ReadRss readRss=new ReadRss(this,recyclerView);
readRss.execute();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int topRowVerticalPosition =
(recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
refreshLayout.setEnabled(topRowVerticalPosition >= 0);
refreshLayout.setEnabled(linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
/*recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
myRecyclerViewAdapter = new MyAdapter(context,feedItems);
//myRecyclerViewAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(myRecyclerViewAdapter);
recyclerView.setLayoutManager(linearLayoutManager);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
CONTENT MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.rssreader.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
You have defined setOnRefreshListener in your refreshLayout but didn't implemented it.
you have to use setOnRefreshListener method on your swipe refresh layout like this.
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// call your Refresh method here
mswipeRefreshLayout.setRefreshing(false);
}
});
You have to set OnRefreshListener to the SwipeRefreshListener and handle the refresh in the callback.
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
#Override
public void onRefresh()
{
// handle your refresh logic
}
});

Navigation Drawer for Multiple Activity

I was having some problem when trying to make my navigation drawer in Android accessible from all Activity. I have a NavigationDrawer.java:
public class NavigationDrawer extends Activity {
static Context context;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mEventSelection;
private String[] mProfileSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mEventSelection = getResources().getStringArray(R.array.event_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
listParent.add(new SampleTO(getString(R.string.eventDrawer),
R.drawable.event));
listDataChild.put(getString(R.string.eventDrawer),
Arrays.asList(mEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
// Navigation drawer with sub menu goes here
public void selectItem(int groupPosition, int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
if (groupPosition == 0) {
switch (selectedPosition) {
case 0:
break;
case 1:
break;
}
// Navigation item for event
else if (groupPosition == 3) {
switch (selectedPosition) {
case 0:
Intent eventMain = new Intent(context, EventMain.class);
context.startActivity(eventMain);
break;
case 1:
Toast.makeText(NavigationDrawer.this, "Analyze Event",
Toast.LENGTH_LONG).show();
break;
}
}
setTitle(mEventSelection[selectedPosition]);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter
.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.amenityDrawer))) {
Toast.makeText(NavigationDrawer.this, "Amenity",
Toast.LENGTH_LONG).show();
setTitle(parentTitle);
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(groupPosition, childPosition);
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(navDrawerView);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And then I navigate to my second class which is EventMain.java when the sub item from navigation drawer is selected:
public class EventMain extends NavigationDrawer {
public static MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
LocationManager locationManager;
public static GraphicsLayer graphicsLayer = null;
public static Callout callout;
private int mYear, mMonth, mDay, mHour, mMinute;
private Calendar c;
static final int DATE_DIALOG_ID = 1;
static final int TIME_DIALOG_ID = 2;
private LinearLayout legendDiv, llNewsFeed, llSearch;
private ListView listview;
private Button btnNewsFeed, btnSearchAddr, btnLegends;
private EditText searchAddrET;
private ImageView ivEventGuide;
public static LinearLayout directionDiv;
public static TextView tvDirection, tvDirectionTitle, tvSearchTitle;
static EventController eventCtrl = new EventController();
static Event eventModel = new Event();
private ListAdapter mAdapter;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
ArcGISRuntime.setClientId("UkIVSWzquykoxCMG");
super.onCreate(savedInstanceState);
setContentView(R.layout.event_main);
context = this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.event_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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
It did shows the navigation drawer icon at the EventMain.java. However, when I try to expand it, it does not work. Any ideas?
Thanks in advance.
The xml layout of my EventMain:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.esri.android.map.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
initExtent="21801.3, 25801.0, 33218.7, 44830.0" >
</com.esri.android.map.MapView>
//Other linear and relative layouts
</FrameLayout>
</LinearLayout>
In EventMain's onCreate() method, setContentView() is being called after the call to the super.onCreate() method. This is causing the DrawerLayout set in the base class, NavigationDrawer, to be replaced, effectively removing the Drawer. To prevent this, we ensure the DrawerLayout has the standard container FrameLayout for main content, and inflate EventMain's layout into that.
The base Activity's layout, main.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" >
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
...
</android.support.v4.widget.DrawerLayout>
And in the Activity subclass, EventMain:
#Override
public void onCreate(Bundle savedInstanceState) {
...
super.onCreate(savedInstanceState);
ViewGroup content = (ViewGroup) findViewById(R.id.event_frame);
getLayoutInflater().inflate(R.layout.event_main, content, true);
...
}

navigation drawer not working

i have a navigation drawer in my app and i am trying to use its content which is a simple counter.whenever i click on the counter my app crashes my logcat shows view not found etc etc.here are my three files start.java is my main java file,fragtasbeeh is my counter fragment and xml file.thnx in advance:
public class Start extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
CustomDrawerAdapter adapter;
List<DrawerItem> dataList;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#076672")));
setContentView(R.layout.activity_start);
// Initializing
dataList = new ArrayList<DrawerItem>();
mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.leftdrawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Add Drawer Item to dataList
dataList.add(new DrawerItem("Search", R.drawable.ic_action_map));
dataList.add(new DrawerItem("compass",
R.drawable.ic_action_location_found));
dataList.add(new DrawerItem("counter", R.drawable.ic_action_good));
dataList.add(new DrawerItem("tings", R.drawable.ic_action_group));
dataList.add(new DrawerItem("about us", R.drawable.ic_action_about));
adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
dataList);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
SelectItem(-1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start, menu);
return true;
}
public void SelectItem(int possition) {
if(possition==-1)
{
setTitle(getResources().getString(R.string.app_name));
}
else{
Fragment fragment = null;
Bundle args = new Bundle();
switch (possition) {
case 0:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 1:
fragment = new FragmentOne();
args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
.getItemName());
args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
.getImgResID());
break;
case 2:
fragment = new FragTasbeeh();
break;
default:
break;
}
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment)
.commit();
mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().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);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return false;
}
public class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
SelectItem(position);
}
}
}
Fragtasbeeh.java
public class FragTasbeeh extends Fragment implements OnClickListener{
int count;
Button reset,add;
TextView counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v=inflater.inflate(R.layout.tasbeeh, container,true);
reset=(Button) v.findViewById(R.id.reset);
add=(Button)v.findViewById(R.id.count);
counter=(TextView)v.findViewById(R.id.editText1);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=count+1;
counter.setText(count);
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count=0;
counter.setText(count);
}
});
return v;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
tasbeeh.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:ems="10"
android:inputType="number"
android:maxHeight="60dp"
android:textColor="#076672" >
<requestFocus />
</EditText>
<Button
android:id="#+id/reset"
android:layout_width="117dp"
android:layout_height="20dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="0.35"
android:paddingLeft="50dp"
android:text="#string/RESET"
android:textAlignment="center"
android:textSize="20dp" />
<Button
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:layout_weight="0.85"
android:text="count" />
</LinearLayout>
the problem was with the xml file, there was a space or alignment problem between button and textview
ive solved it by making a relativelayout

Categories