为每个回收站视图android调用一个类对象

时间:2017-11-17 05:43:08

标签: android interface android-recyclerview recycler-adapter

有一种情况,我有一个具有回收者视图的活动,我有它的适配器,有一个模型类,用于三个文本视图的回收者视图位置,纬度,经度来自数据库。现在我希望第四个回收区域查看距离。距离由另一个类和回调函数中的返回距离计算。我在哪里初始化recyclerview中该类的对象,以便它相对于每个项目的纬度和长度连续更新距离。

返回单纬度,长

的距离的代码
 compassManager = new CompassManager(getApplicationContext(), this);
    if (isLocationServiceEnabled()) {
        Log.i("FloatingViewServie","Location Service Enabled");
        // i want to pass latitude and longitude of UserLocations below to 
        // get distance on each row
        compassManager.startNavigating(33.69206669, 73.03208828);
        compassManager.getLocation().getLatitude();
        compassManager.getLocation().getLongitude();

    }

返回连续更新距离的回调方法

    @Override
public void onDistanceUpdate(float distance) {
    //this distance need to be on recyclerview for each row
}

Recyclerview适配器

public class ActiveLocationsAdapter extends RecyclerView.Adapter<ActiveLocationsAdapter.MyViewHolder> {
public interface OverflowOptions
{
    public void edit(int position,UserLocations userLocations);
    public void delete();
}
private List<UserLocations> userLocationsList;

FirebaseDatabase database;
DatabaseReference rootRef;
private FirebaseAuth mAuth;
FirebaseUser user;
Context context;
OverflowOptions overflowOptionsCallback;
public ActiveLocationsAdapter(Context context,List<UserLocations> locationsList,OverflowOptions callback) {
    this.userLocationsList = locationsList;
    database = FirebaseDatabase.getInstance();
    rootRef = database.getReference();
    mAuth = FirebaseAuth.getInstance();
    user = mAuth.getCurrentUser();
    this.context=context;
    overflowOptionsCallback=callback;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.row_active_locations, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    // model class that have latitude and longitude for each row
    final UserLocations userLocations = userLocationsList.get(position);
    Log.i("aaposition",String.valueOf(holder.getAdapterPosition()));
    holder.name.setText(userLocations.getName());
   // holder.distance.setText(String.valueOf(userLocations.getLatitude()));
  //  holder.direction.setText(String.valueOf(userLocations.getLongitude()));
    holder.overflow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //creating a popup menu
            PopupMenu popup = new PopupMenu(context, holder.overflow);
            //inflating menu from xml resource
            popup.inflate(R.menu.locations_overflow_menu);
            //adding click listener
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                        case R.id.action_edit:
                            overflowOptionsCallback.edit(holder.getAdapterPosition(), userLocations);
                            break;
                        case R.id.action_delete:

                            break;
                    }
                    return false;
                }
            });
            //displaying the popup
            popup.show();

        }
    });



}

@Override
public int getItemCount() {
    return userLocationsList.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView name, distance, direction;
    public ImageView overflow;

    public MyViewHolder(View view) {
        super(view);
        name = (TextView) view.findViewById(R.id.name);
        distance = (TextView) view.findViewById(R.id.distance);
        direction = (TextView) view.findViewById(R.id.direction);
        overflow = (ImageView) view.findViewById(R.id.overflow);
    }
}

} 模型类

public class UserLocations {

String id;
String name;
double latitude;
double longitude;
String status;

public UserLocations() {
}

public UserLocations(String id, String name, double latitude, double longitude, String status) {
    this.id=id;
    this.name = name;
    this.latitude = latitude;
    this.longitude = longitude;
    this.status = status;
}
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public double getLatitude() {
    return latitude;
}

public void setLatitude(double latitude) {
    this.latitude = latitude;
}

public double getLongitude() {
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

public String getStatus() {return status;}

public void setStatus(String status) {this.status = status;}

} Recyclerview行

<?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="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true"
android:background="?android:attr/selectableItemBackground"
android:orientation="vertical">

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:textColor="@color/heading"
    android:textSize="16dp"
    android:textStyle="bold" />
<TextView
    android:id="@+id/distance_lable"
    android:layout_below="@id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/subheading"
    android:text="Distance : "/>
<!-- To display distance-->
<TextView
    android:id="@+id/distance"
    android:layout_below="@id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/subheading"
    android:layout_toRightOf="@+id/distance_lable"
    />

<TextView
    android:layout_below="@id/name"
    android:id="@+id/direction_lable"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/distance"
    android:textColor="@color/subheading"
    android:text=" Direction : "/>
<!-- To display direction-->
<TextView
    android:id="@+id/direction"
    android:layout_below="@id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/subheading"
    android:layout_toEndOf="@+id/direction_lable"/>

<ImageButton
    android:id="@+id/overflow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_marginRight="5dp"
    android:background="@drawable/ic_more_vert_black_24dp"
    />
  </RelativeLayout>

具有recyclerview的主要活动

public class MainActivity extends AppCompatActivity
        implements CurrentLocationManager.ResultSupplier,NavigationView.OnNavigationItemSelectedListener,ActiveLocationsAdapter.OverflowOptions{
    private static final int CODE_DRAW_OVER_OTHER_APP_PERMISSION = 2084;
    public static final int REQUEST_FINE_LOCATION = 1;
    public static final String TAG= MainActivity.class.getSimpleName();
    private PrefManager prefManager;
    CurrentLocationManager currentLocationManager;;
    private List<UserLocations> userLocationsList = new ArrayList<>();
    private RecyclerView recyclerView;
    private ActiveLocationsAdapter mAdapter;
    FirebaseDatabase database;
    DatabaseReference rootRef;
    private FirebaseAuth mAuth;
    FirebaseUser user;
    ProgressDialog progressDoalog;

    Context context,interfaceContext;
    ImageButton imgBtnSaveLocation;
    private double lattitude,longitude;
    Switch toggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermissions(this);
        permissionCheck();
        context=getApplicationContext();

        imgBtnSaveLocation=(ImageButton)findViewById(R.id.main_activity_save_btn) ;
        progressDoalog = new ProgressDialog(MainActivity.this);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        toggle=(Switch)findViewById(R.id.active_locations_switch);

        mAdapter = new ActiveLocationsAdapter(getApplicationContext(),userLocationsList,this);
        prefManager = new PrefManager(this);
        prefManager.setFirstTimeLaunch(false);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //database reference pointing to root of database
        database = FirebaseDatabase.getInstance();
        rootRef = database.getReference();
        // gives current authenticated user
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        recyclerView.setAdapter(mAdapter);

        progressDoalog.setMessage("Fetching Data. . .");
        progressDoalog.show();
        // get and update data on View on any change in database
        rootRef.child(user.getDisplayName()).child("active_locations").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
                    UserLocations locations = noteDataSnapshot.getValue(UserLocations.class);
                    if(locations.getStatus().equals("active")) {
                        if (!contains((ArrayList<UserLocations>) userLocationsList, locations)) {

                            userLocationsList.add(locations);
                        }
                    }
                }
                mAdapter.notifyDataSetChanged();
                progressDoalog.dismiss();
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
            }
        });

        // button click that get current location and save to database
        imgBtnSaveLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG,"onclick");
                getLocation();
            }
        });
        // turn the tracking on and off
        toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                Toast.makeText(context, "Toggle on", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(context, "Toggle off", Toast.LENGTH_SHORT).show();
            }
        });



        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);



    }
    public void permissionCheck()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(getApplicationContext())) {


            //If the draw over permission is not available open the settings screen
            //to grant the permission.
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, CODE_DRAW_OVER_OTHER_APP_PERMISSION);
        } else {

        }
    }
    private void requestPermissions(Context context) {
        ActivityCompat.requestPermissions((Activity) context,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_FINE_LOCATION);
    }
    private boolean checkPermissions(Context context) {
        if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
              requestPermissions(context);
            return false;
        }
    }

    @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) {
            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_active_locations) {
            startActivity(new Intent(getApplicationContext(),ActiveLocationsActivity.class));

        } else if (id == R.id.nav_tracked_locations) {
            startActivity(new Intent(getApplicationContext(),TrackedLocationsActivity.class));

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {
            AuthUI.getInstance()
                    .signOut(this)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        public void onComplete(@NonNull Task<Void> task) {
                            // user is now signed out
                            startActivity(new Intent(getApplicationContext(), SignUpActivity.class));
                            finish();  }
                    });

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    public void getLocation()
    {

        currentLocationManager = new CurrentLocationManager(context,this);
        currentLocationManager.getUpdatedLocation();
    }

    /**
     * Compares two array list
     * @param list
     * @param locations
     * @return
     */
    boolean contains(ArrayList<UserLocations> list, UserLocations locations) {
        for (UserLocations item : list) {
            if (item.getId().equals(locations.getId())&&item.getName().equals(locations.getName())&&item.getLatitude()==locations.getLatitude()&&item.getLongitude()==locations.getLongitude()&&item.getStatus().equals(locations.getStatus())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void result(double lat, double longi) {
        lattitude=lat;
        longitude=longi;
        Log.i("callback result",String.valueOf(lat)+","+String.valueOf(longi));
    }

    @Override
    public void edit(final int position, final UserLocations userLocations) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = this.getLayoutInflater();
        final View dialogView = inflater.inflate(R.layout.dialog_edit_location_name, null);
        dialogBuilder.setView(dialogView);

        final EditText rename = (EditText) dialogView.findViewById(R.id.name);

        dialogBuilder.setTitle("Rename Location");
        //dialogBuilder.setMessage("hello");
        dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

                renameLocation(userLocations.getName(),rename.getText().toString());
                userLocations.setName(rename.getText().toString());
                userLocationsList.set(position, userLocations);


            }
        });
        dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //pass
            }
        });
        AlertDialog b = dialogBuilder.create();
        b.show();
    }

    @Override
    public void delete() {

    }
    public void renameLocation(final String name, final String renameLocation) {
        Log.i("Interface","renameLocation");
        Query renameQuery= rootRef.child(user.getDisplayName()).child("active_locations").orderByChild("name").equalTo(name);
        renameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot child : dataSnapshot.getChildren()) {
                    String child_name = (String) child.child("name").getValue();

                    if (child_name.equals(name)){
                        child.getRef().child("name").setValue(renameLocation);
                        Log.i("Rename Location","child renamed");
                    }


                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }
}

0 个答案:

没有答案