简体   繁体   English

如何在不使用 position 的情况下打开不同的活动

[英]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.我想知道除了 position 命令之外还有其他命令可以打开不同的活动。 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.因为我在搜索时遇到问题,它变成了字母顺序,当我单击该项目时,它给了我不同的结果,因为 position 正在改变。 I dont know what is the problem of my code is it the search function or the position command to open different new activities.我不知道我的代码有什么问题,是搜索 function 还是 position 命令打开不同的新活动。

MainAdapter.class主适配器.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 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:例如,您在列表中有 3 个项目,例如:

[
  {
    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.您可以使用“holder.getAdapterPosition”代替“position”来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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