简体   繁体   中英

How to different open activities without using position

This is a recipe app with categories and sub categories. I want to know is there any other command to open different activities besides position command. Because I have a problem when searching it becames alphabetical order, when i click the item it give me different result because the position is changing. I dont know what is the problem of my code is it the search function or the position command to open different new activities.

MainAdapter.class

public class MainAdapter extends FirebaseRecyclerAdapter<MainModel,MainAdapter.myViewHolder> {

private Context context;

/**
 * Initialize a {@link RecyclerView.Adapter} that listens to a Firebase query. See
 * {@link FirebaseRecyclerOptions} for configuration options.
 *
 * @param options
 */
public MainAdapter(@NonNull FirebaseRecyclerOptions<MainModel> options) {
    super(options);
}

@Override
protected void onBindViewHolder(@NonNull MainAdapter.myViewHolder holder, int position, @NonNull MainModel model) {

    holder.categoryName.setText(model.getName());
    holder.categoryDesc.setText(model.getDescription());

    Glide.with(holder.categoryImage.getContext())
            .load(model.getImage())
            .placeholder(R.drawable.common_google_signin_btn_icon_dark)
            .error(R.drawable.common_google_signin_btn_icon_dark_normal)
            .into(holder.categoryImage);

    context = holder.itemView.getContext();

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent;
            switch (position){
                case 0:
                    intent =  new Intent(context, ChickenActivity.class);
                    break;
                case 1:
                    intent =  new Intent(context, PorkActivity.class);
                    break;
                case 2:
                    intent =  new Intent(context, BeefActivity.class);
                    break;
                case 3:
                    intent =  new Intent(context, SeafoodActivity.class);
                    break;
                default:
                    intent =  new Intent(context, VegetableActivity.class);
                    break;
            }
            context.startActivity(intent);
        }

    });
}

@NonNull

@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item,parent,false);
    return new myViewHolder(view);
}

class myViewHolder extends RecyclerView.ViewHolder{

    ImageView categoryImage;
    TextView categoryName, categoryDesc;


    public myViewHolder(@NonNull View itemView) {
        super(itemView);

        categoryImage = (ImageView)itemView.findViewById(R.id.categoryImage);
        categoryName = (TextView)itemView.findViewById(R.id.categoryName);
        categoryDesc = (TextView)itemView.findViewById(R.id.categoryDesc);


    }
}

}

MainActivity.class

public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;
MainAdapter mainAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recyclerView = (RecyclerView)findViewById(R.id.recView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    FirebaseRecyclerOptions<MainModel> options =
            new FirebaseRecyclerOptions.Builder<MainModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("category"), MainModel.class)
                    .build();

    mainAdapter = new MainAdapter(options);
    recyclerView.setAdapter(mainAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    mainAdapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    mainAdapter.stopListening();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.search,menu);
    MenuItem item = menu.findItem(R.id.search);
    SearchView searchView = (SearchView)item.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            txtSearch(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String query) {
            txtSearch(query);
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

private void txtSearch(String str)
{
    FirebaseRecyclerOptions<MainModel> options =
            new FirebaseRecyclerOptions.Builder<MainModel>()
                    .setQuery(FirebaseDatabase.getInstance().getReference().child("category").orderByChild("name").startAt(str).endAt(str+"~"), MainModel.class)
                    .build();

    mainAdapter = new MainAdapter(options);
    mainAdapter.startListening();
    recyclerView.setAdapter(mainAdapter);
}

}

Instead of tying the Activity to a number you should tie it to a tag or some identifier. For example, you have 3 items in the list Like:

[
  {
    name: "chickenwings"
  },
  {
    name: "octopus"
  },
  {
    name: "tomato"
  }
]

Instead you can have additional information like the activity the item should correlate with, for example

[
  {
    name: "chickenwings",
    category: "chicken"
  },
  {
    name: "octopus",
    category: "seafood"
  },
  {
    name: "tomato",
    category: "vegetable"
  }
]

This will help you update your code like below

holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent;
            val category = model.getCategory()
            switch (category){
                case "chicken":
                    intent =  new Intent(context, ChickenActivity.class);
                    break;
                case "pork":
                    intent =  new Intent(context, PorkActivity.class);
                    break;
                case "beef":
                    intent =  new Intent(context, BeefActivity.class);
                    break;
                case "seafood":
                    intent =  new Intent(context, SeafoodActivity.class);
                    break;
                case "vegetable":
                default:
                    intent =  new Intent(context, VegetableActivity.class);
                    break;
            }
            context.startActivity(intent);
        }

    });

You can use "holder.getAdapterPosition" instead of "position" to solve this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM