Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

android - particular title(fetched from api) using searchview?

I want something like this:

so the thing is, what I exactly want is when user type particular topic name(if present in-app) in searchview it should able give suggestions and if found it should open that topic activity (just like Facebook, Instagram,...etc searches)..and those title are coming from API(which I have successfully displayed in other activities)..like this:

..what will the logic for it??? need help... Thanks

so I have just included searchview in XML like this-->

  <SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:queryHint="Search Here"
    android:iconifiedByDefault="false"
    android:layout_alignParentTop="true"
    android:background="@drawable/search_bar"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="20dp"
    android:pointerIcon="crosshair"
    android:theme="@style/Widget.AppCompat.SearchView"
    android:focusedByDefault="true"
    />

Need help..thanks in advance....

here is my json:

[{"id":"11","title":"TextView"},{"id":"10","title":"Edit Text"},{"id":"9","title":"ImageView"},{"id":"8","title":"Button "},{"id":"7","title":"CheckBox"},{"id":"6","title":"RadioButton & RadioGroup"},{"id":"5","title":"DatePicker"},{"id":"4","title":"TimePicker"},{"id":"3","title":"Switch"},{"id":"1","title":"Simple & Custom Toast"}]

here is my activity: for

public class StartLearning extends AppCompatActivity {
private RecyclerView recyclerView;
private SLAdapter slAdapter;
ProgressDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.startlearning_layout);
    progressDialog = new ProgressDialog(StartLearning.this);
    progressDialog.setMessage("Loading....");
    progressDialog.show();
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        /*Create handle for the RetrofitInstance interface*/
        SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
        Call<List<SlModel>> call = service.getMySlmodel();

        call.enqueue(new Callback<List<SlModel>>() {
            @Override
            public void onResponse(Call<List<SlModel>> call, Response<List<SlModel>> response) {
                progressDialog.dismiss();
                generateDataList(response.body());
                Log.e("hello", String.valueOf(response.body()));
            }

            @Override
            public void onFailure(Call<List<SlModel>> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
private void generateDataList(List<SlModel> employeeList) {
    recyclerView = findViewById(R.id.SLrecycle);
    LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(manager);
    recyclerView.setHasFixedSize(true);
    slAdapter = new SLAdapter(getApplicationContext(),employeeList);
    recyclerView.setAdapter(slAdapter);
}

adapter:

public class SLAdapter extends RecyclerView.Adapter<SLAdapter.CustomViewHolder> {

List<StartLearning.SlModel> Slmdel;
Context context;

public SLAdapter(Context context,List<StartLearning.SlModel> employees) {
    this.Slmdel = employees;
    this.context=context;
}

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

    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
    // TipsModel employee = employees.get(position);
    //// holder.employeeName.setText(employees.get(position).getTips());
    holder.textView.setText(String.valueOf(position+1)+". ");
    holder.employeeName.setText(Slmdel.get(position).getTitle());
}

@Override
public int getItemCount() {
    return Slmdel.size();
    //return (employees == null) ? 0 : employees.size();

}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView employeeName;
    TextView textView;

    public CustomViewHolder(View view) {
        super(view);
        employeeName = (TextView) view.findViewById(R.id.Sl2);
        textView=view.findViewById(R.id.Sl1);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =  new Intent(context, NextSLactivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("title", Slmdel.get(getAdapterPosition()).getTitle());
               intent.putExtra("idSLnext", Slmdel.get(getAdapterPosition()).getId());
                //Log.e("ashwini",WAmdel.get(getAdapterPosition()).getId());
                context.startActivity(intent);

            }
        });
    }
}

onclick of item(example :textview)

activity:one of the items(example :textview)

public class JavaFragment extends Fragment {

private RecyclerView recyclerView;
private NextSLJavaAdapter adapter;
private NextSLModel DescriptList;
ProgressDialog progressDialog;
public JavaFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.nextsl_layout, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Toolbar toolbar = (Toolbar) getView().findViewById(R.id. toolbar );
   // setSupportActionBar( toolbar );
    //if (getSupportActionBar() != null) {
      //  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       // getSupportActionBar().setDisplayShowHomeEnabled(true);
    //}
    progressDialog = new ProgressDialog(getContext());
    progressDialog.setMessage("Loading....");
    progressDialog.show();
    Intent intent = getActivity().getIntent();
    String title = intent.getStringExtra("title");
    //getSupportActionBar().setTitle(title);
    String id = intent.getStringExtra("idSLnext");
    Log.e("ashwini", String.valueOf(id));

    /*Create handle for the RetrofitInstance interface*/
    SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
    Call<NextSLModel> call = service.getnextslmodel(id);
    call.enqueue(new Callback<NextSLModel>() {
        @Override
        public void onResponse(Call<NextSLModel> call, Response<NextSLModel> response) {
            progressDialog.dismiss();
            DescriptList=response.body();
            generateDataList(DescriptList);

        }

        @Override
        public void onFailure(Call<NextSLModel> call, Throwable t) {
             progressDialog.dismiss();

            Toast.makeText(getContext(), "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
        }
    });

}
private void generateDataList(NextSLModel photoList) {
    recyclerView = getView().findViewById(R.id.nextSLrecycle);
    LinearLayoutManager manager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(manager);
    recyclerView.setHasFixedSize(true);
    adapter = new NextSLJavaAdapter(getContext(),photoList);
    recyclerView.setAdapter(adapter);
}
}

adapter:

public class NextSLJavaAdapter extends RecyclerView.Adapter<NextSLJavaAdapter.CustomViewHolder> {

NextSLModel Slmdel;
Context context;

public NextSLJavaAdapter(Context context, NextSLModel employees) {
    this.Slmdel = employees;
    this.context = context;
}

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

    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
    // TipsModel employee = employees.get(position);
    //// holder.employeeName.setText(employees.get(position).getTips());
 /////////   holder.textView.setText(String.valueOf(position + 1) + ". ");
    holder.employeeName.setText(Slmdel.getJava());
    Log.e("sl",Slmdel.getJava());
}

@Override
public int getItemCount() {
    return 1;
    //return (employees == null) ? 0 : employees.size();

}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView employeeName;
    TextView textView;

    public CustomViewHolder(View view) {
        super(view);
        employeeName = (TextView) view.findViewById(R.id.detailsStartLearning);
        textView = view.findViewById(R.id.Sl1);}}}

look at this search activity:

public class Search extends AppCompatActivity {
SearchView searchView;
RecyclerView recyclerView;
SearchAdapter slAdapter;
List<StartLearning.SlModel> movieList;
ChipGroup chipGroup;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    searchView=findViewById(R.id.searchView);

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

        @Override
        public boolean onQueryTextChange(String newText) {
            searchForResults(newText);
            return false;
        }
    });
    //new code
    chipGroup = findViewById(R.id. chipGroup);

    searchView.onActionViewExpanded();
    searchView.setIconified(true);
}
public void searchForResults(String search){
    //here make an api call to get the results, complete the code here
    SLApiSevice service = SLApiClient.getRetrofitInstance().create(SLApiSevice.class);
    retrofit2.Call<List<StartLearning.SlModel>> call = service.getMySlmodel();

    call.enqueue(new Callback<List<StartLearning.SlModel>>() {
        @Override
        public void onResponse(retrofit2.Call<List<StartLearning.SlModel>> call, Response<List<StartLearning.SlModel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a new Chip Material Component in android. Which can be used to fullfill the requirements. I belive you are currently using some recyclerview to display those search items instead of using this use ChiGroup to hold those values.a

Below is some sample code to do

First add this to your gradle for using the external libarary dependency

implementation 'com.google.android.material:material:1.0.0-alpha1'

Then in your desired layout below the search view place this xml code.

<com.google.android.material.chip.ChipGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:id="@+id/chipGroup"
    app:chipSpacing="25dp"/>

The ChipGroup will hold the Chip items which will be added dynamically.

So now in your search activity/fragment just get a reference of this layout group.

        public class Search extends AppCompatActivity {
        SearchView searchView;
        ChipGroup chipGroup;

        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.search);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            searchView = findViewById(R.id.searchView);
            //new code 
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    searchForResults(newText);
                    return false;
                }
            });
            //new code
            chipGroup = findViewById(R.id. chipGroup);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                getSupportActionBar().setDisplayShowHomeEnabled(true);
            }
        }
        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            if (item.getItemId() ==android.R.id.home) {
                finish();
            }
            return super.onOptionsItemSelected(item);
        }
        @Override
        public void onBackPressed() {
            super.onBackPressed();
        }

        //new code
        public void searchForResults(String search){
          //here make an api call to get the results, complete the code here
          call.enqueue(new Callback<List<StartLearning.SlModel>>() {
              @Override
              public void onResponse(retrofit2.Call<List<StartLearning.SlModel>> call, Response<List<StartLearning.SlModel>> response) {

                 List<StartLearning.SlModel> list = response.body();
                 //after getting the results pass to addChips()
                 addChips(list)
                 Log.d("TAG","Response = "+movieList);


             }

             @Override
             public void onFailure(retrofit2.Call<List<StartLearning.SlModel>> call, Throwable t) {
                  Log.d("TAG","Response = "+t.toString());

             }
          });
        }

        //just call this when you get the search result from the api with your custom model and where ever it is applicable.
        public void addChips(List<StartLearning.SlModel> searchItems){
          for (StartLearning.SlModel item : searchItems) {
             Chip mChip = (Chip) this.getLayoutInflater().inflate(R.layout.item_chip, null, false);
             mChip.setText(item.title);
             int paddingDp = (int) TypedValue.applyDimension(
                     TypedValue.COMPLEX_UNIT_DIP, 10,
                     getResources().getDisplayMetrics()
             );
             mChip.setPadding(paddingDp, 0, paddingDp, 0);
             mChip.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                // Handle the click here
                }
             });
             chipGroup.removeAllViews();
             chipGroup.addView(mChip);
         }
       }
   }

I can't find the relevant code in Search activity to give an example. but the general idea is as below.

1) You add a ChipGroup to hold the Chip Views which will be added dynamically in your search view xml. 2) User Search something and you get the api response and you create a model based list. 3) you then iterate over the list one by one and create the dynamic chips.

4) But first create an item_chip.xml file with below content.

<com.google.android.material.chip.Chip xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:id=@+id/smallChip
style="@style/Widget.MaterialComponents.Chip.Choice"
android:textAppearance="?android:attr/textAppearance"
android:textColor="@color/secondaryTextColor"
app:chipBackgroundColor="@color/colorAccent" />

5) Now we are going to just inflate this layout file and add this to ChipGroup in for loop which we received earlier.

6) so the sample code goes like this to add the dynamic chips to ChipGroup. Here im using String as search items for simplicity you can use your own model here.

public void addChips(ArrayList<String> searchItems){
    for (String item : searchItems) {
        Chip mChip = (Chip) this.getLayoutInflater().inflate(R.layout.item_chip, null, false);
        mChip.setText(item);
        int paddingDp = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 10,
                getResources().getDisplayMetrics()
        );
        mChip.setPadding(paddingDp, 0, paddingDp, 0);
        mChip.setOnClickListener(new OnClickListener() {
           @Override
           public void onClick(View view) {
           // Handle the click here
           }
        });
        chipGroup.addView(mChip);
    }
}

now we have just added the chips dynamically to chipGroup which we declared earlier in search view layout . But this can also be done using Recyclerview instead of using ChipGropup just add the Chip View inside the recyclerview items and get a reference and set the text as you do with text views nothing to change except in adapter and item layout.

Edit: 4/1/20

Place the ChipGrop into the below XML file with search view. The idea is that the search view input box will be on top and the suggestions from the search will be just below the search box to give changing search results just right there on same screen. so call the search-related API call in the Search activity itself and pass the results to the sample method addChips() I have mentioned above.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

<SearchView
    android:id="@+id/searchView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:queryHint="Search Here"
    android:iconifiedByDefault="false"
    android:layout_alignParentTop="true"
    android:background="@drawable/search_bar"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="20dp"
    android:pointerIcon="crosshair"
    android:theme="@style/Widget.AppCompat.SearchView"
    android:focusedByDefault="true"/>

<com.google.android.material.chip.ChipGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:id="@+id/chipGroup"
        app:chipSpacing="25dp"/>

</LinearLayout>

For more info read below blogs:

Material Design Chips

How to use Chips Blog

How to add Chips to ChipsGroup


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...