Converting listview to ListView with custom rows - android-studio

I am trying to convert my basic list view into a complex list view. I tried doing this by creating a product adapter. I keep getting an error on the super part saying "objects() in objects cannot be applied". I have not done this before, I was following a tutorial.
public class ProductAdapter {
ProductAdapter(Context context, String[] addProduct){
super(context,R.layout.list_item, addProduct);
}
#Override
public View getView(int position,View convertView, ViewGroup parent){
LayoutInflater momentsInflater = LayoutInflater.from(getContext());
View customView = momentsInflater.inflate(R.layout.list_item, parent, false);
ImageView imageView = (ImageView) customView.findViewById(R.id.imageView);
TextView momentsText = (TextView) customView.findViewById(R.id.textViewName);
ImageView momentsImage = (ImageView) customView.findViewById(R.id.imageView);
}
};
MainActivity
public class MainActivity extends Activity {
private ListView listView;
private String[] details;
public static ArrayList<Product> product = new ArrayList<>();
boolean firstRun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
}
#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 presses on the action bar items
switch (item.getItemId()) {
case R.id.action_AddProduct:
startActivity(new Intent(MainActivity.this, Activity_addProduct.class));
case R.id.action_Information:
startActivity(new Intent(MainActivity.this, Activity_addProduct.class));
return true;
case R.id.action_Home:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
DatabaseHandler db = new DatabaseHandler(this);
String[] productStrings;
if (firstRun) {
String[] placeHolterStrings = {"", ""};
productStrings = placeHolterStrings;
firstRun = false;
} else {
product = db.getAllContacts();
productStrings = new String [product.size()];
for (int i = 0; i < product.size(); i++) {
productStrings[i] = product.get(i).toString();
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, productStrings);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
);
}
}
Myproduct class
public class Product {
private int id;
private String productName;
private String productModel;
public Product(int id, String productName, String productModel) {
this.id = id;
this.productName = productName;
this.productModel = productModel;
}
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setName(String productName) {
this.productName = productName;
}
public String getProductModel() {
return productModel;
}
public void setProductModel(String productModel) {
this.productModel = productModel;
}
#Override
public String toString() {
return this.productName + " " + this.productModel;
}
}
List_item.xml
<LinearLayout 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/imageView"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#android:color/darker_gray"
android:padding="8dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="first + last name"
android:textSize="16dp" />
<TextView
android:id="#+id/textViewDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="details of the candidate"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
A complex list view is the example below:

Related

I have to apply autocomplete inside home fragment in bottom nav menu but I am unable to type anything in search tab

I have to apply autocomplete inside home fragment in bottom nav menu but I am unable to type anything in search tab.
I am getting this interface but when I try to enter anything in the search tab it doesn't take any input as if it don't even open the keyboard:
My JavaScript code for homefragment is as follows:
public class HomeFragment extends Fragment implements OnMapReadyCallback {
private HomeViewModel homeViewModel;
FragmentHomeBinding binding;
private GoogleMap mMap;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private Marker marker;
private MarkerOptions markerOptions;
SupportMapFragment mapFragment;
#Override
public void onDestroy() {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
super.onDestroy();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
binding = FragmentHomeBinding.inflate(inflater, container, false);
homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
init();
return binding.getRoot();
}
private void setupAutoCompleteFragment()
{
SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
Log.e("Error", status.getStatusMessage());
}
});
}
#SuppressLint("MissingPermission")
private void init() {
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(10f);
locationRequest.setInterval(3000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(1500);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(), locationResult.getLastLocation().getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
}
;
};
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
private void gotoLatLng(double latitude, double longitude, float v) {
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,18f);
mMap.animateCamera(update);
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
Dexter.withContext(getContext()).
withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#SuppressLint("MissingPermission")
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationButtonClickListener(() -> {
fusedLocationProviderClient.getLastLocation().addOnFailureListener(e -> Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show())
.addOnSuccessListener(location -> {
LatLng userLatLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userLatLng, 21f));
});
return true;
});
View locationButton = ((View)mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,RelativeLayout.TRUE);
params.setMargins(0,0,0,50);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(), "Permission" + permissionDeniedResponse.getPermissionName() + "" + "was denied !", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
}).check();
}
}
And the layout used is for same fragment is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<FrameLayout 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"
tools:context=".ui.home.HomeFragment">
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
android:layout_gravity="center_horizontal|bottom" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/backcolor">
<fragment
android:id="#+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Place"
android:background="#fff"
android:name="com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment"
/>
</androidx.cardview.widget.CardView>
</FrameLayout>

SearchView retrieving wrong data with List View

When searching for an item, I'm able to retrieve the Title, Artist, and Image for the respective Songs. However, the first 2 items displayed in the ListView when clicked on keeps returning the last song in my list instead of the correct song that is being displayed.
E.g, When clicking on "Life is Good" or "Good as hell", the song "First Time" will be displayed instead. However "Perfect", "Lemon", and "Autopilot" are working fine. These are the only codes used to search! SearchByTitle and GetTitle() are taken from the files where the songs are hardcoded in!
My Activity:
ListView listView;
ArrayList<String> stringArrayList = new ArrayList<>();
ArrayAdapter<String> adapter;
private SongCollection songCollection = new SongCollection();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = findViewById(R.id.list_view);
stringArrayList.add("Life is Good");
stringArrayList.add("Good As Hell");
stringArrayList.add("Perfect");
stringArrayList.add("Lemon");
stringArrayList.add("Autopilot");
stringArrayList.add("First Time");
adapter = new ArrayAdapter<>(SearchActivity.this, android.R.layout.simple_list_item_1, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),
adapter.getItem(i), Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String value = listView.getItemAtPosition(i).toString();
Song selectedSong = songCollection.searchByTitle(value);
AppUtil.popMessage(view.getContext(), "Streaming song: " + selectedSong.getTitle());
sendDataToActivity(selectedSong);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.my_menu, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
XML to my Activity:
<?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"
android:background="#404040"
tools:context=".SearchActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#404040">
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#FFFFFF"
android:divider="#color/white"
android:dividerHeight="2dp"
tools:listitem="#android:layout/simple_list_item_1">
</ListView>
</LinearLayout>
</RelativeLayout>
It happens because you need to create a new list which would contain the search results, you don't have to do the search operation with your original list which isstringArrayList
Instead create a new list which is mylist in this case, and store the search results and call that list in onQueryTextChange
Create this method, I modified the code according to your code
private void search(String str) {
ArrayList<String> myList = new ArrayList<>();
for (Quote object : stringArrayList) {
if (object.GetTitle().toLowerCase().contains(str.toLowerCase())) {
myList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(this, myList);//, swiper
recyclerView.setAdapter(adapterClass);
}
Now, call this method under search setOnQueryTextListener, like this
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(newText);
return true;
}
});
OPTIONAL
And one more modification which you can do is you can check setOnQueryTextListener when ever there is some text in it, like this
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
search(s);
return true;
}
});
}
If my answer solves your problem you can give me an up-vote and mark my answer as correct, by clicking on the gray tick button beside the starting of my answer, which will then turn green!

How do I Remove Cell Padding in a Gridview

I'm hoping someone can help me. I have created a Sudoku app. I have a grid view that shows string text from a list view. I have a problem with my layout of the Grid View on my phone and tablet; , see 1st and 2nd screens below .
What I'm trying to do is set the screen, so the grid display neatly just above the numbers 1 to 5. Ideally I'd like it to render appropriately on tablet and phone.
On a Phone the last row of the sudoku grid showing underneath the first set of button button See firstImage. Whereas on a Tablet there is a huge gap between the gridvview and the Buttons
What I have I tried so far:
I tried android:layout_above btn1. But that chopped off the last row of the sudoku grid and I had to drag the grid up and down to see the last row on a phone. It also caused the app to crash of a phone. Not good.
I tried putting a frame layout inside the relative layout and putting the gridview inside of that. But that had the also chopped off the last row of the sudoku grid as per layout_above.
Really what I'd like to do is, on a phone I would like to remove or reduce the padding above and below each number in each cell in the grid view. As the cell padding makes each cell in the grid 2 - 3 times bigger than it needs to be. This is a problem on a 5" mobile phone screen. I have tried the following and none of them worked.
How do I get rid of unwanted padding in a Listview row
android:gravity - Made no Difference
How to avoid space between imageview and gridview in linearlayout
listSelector=”#null” - Made no difference
Removing the extra padding in a GridView in android
stretchMode(0); - Everything disappeared.
How do I get rid of unwanted padding in a Listview row
view.setMinimumHeight(0); - Made no difference.
I also tried view.setPadding(); it was useful in that the padding on the left hand side was removed, but it didn't remove the papdding at the top or bottom.
view.setPadding(dpToPx(0, parent), 0, 0, 0);
I am at a loss at this stage about how to move this forward and am worried that trying all these different things is making me more confused. If someone could point me in the correct direction I'd be very grateful. Code is shown below.
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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.admin1.sudoku.MainActivity"
android:background="#663399"
tools:showIn="#layout/activity_main">
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn1Label"
android:layout_above="#+id/btn6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/btn2"
/>
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn2Label"
android:layout_above="#+id/btn7"
android:layout_toLeftOf="#+id/btn8"
android:layout_toStartOf="#+id/btn8" />
<Button
android:id="#+id/btn3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn3Label"
android:layout_alignTop="#+id/btn2"
android:layout_toRightOf="#+id/btn2"
android:layout_toEndOf="#+id/btn2" />
<Button
android:id="#+id/btn4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn4Label"
android:layout_alignTop="#+id/btn3"
android:layout_toRightOf="#+id/btn3"
android:layout_toEndOf="#+id/btn3" />
<Button
android:id="#+id/btn5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn5Label"
android:layout_alignTop="#+id/btn4"
android:layout_toRightOf="#+id/btn4"
android:layout_toEndOf="#+id/btn4" />
<Button
android:id="#+id/btn6"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn6Label"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn7"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn7Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn6"
android:layout_toEndOf="#+id/btn6" />
<Button
android:id="#+id/btn8"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn8Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn7"
android:layout_toEndOf="#+id/btn7" />
<Button
android:id="#+id/btn9"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn9Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn3"
android:layout_toEndOf="#+id/btn3" />
<Button
android:id="#+id/btn0"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn0Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn9"
android:layout_toEndOf="#+id/btn9" />
<Button
android:id="#+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnCheckLabel"
android:layout_below="#+id/gridView1"
android:layout_alignTop="#+id/btn5"
android:layout_toRightOf="#+id/btn5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/btnHint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnHintLabel"
android:layout_alignTop="#+id/btn0"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/btnCheck"
android:layout_alignStart="#+id/btnCheck" />
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="9"
android:columnWidth="0dp"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:clipChildren="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#C0C0C0"
android:padding="5dp"
android:textSize="12sp"
android:stretchMode="columnWidth"
android:gravity="clip_vertical"
/>
</RelativeLayout>
MainActivity.java
package com.example.admin1.sudoku;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.graphics.Color;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import android.content.res.Resources;
import android.media.MediaPlayer;
public class MainActivity extends AppCompatActivity {
// Class that holds the creation of a Sudoku Puzzle
private SudokuPuzzle clsSudoku;
//Variables used throughout the program.
private final int iMaxCells = 81;
private String[] stResult; // Holds the solution to the current puzzle
private int[] iExcluded; // Holds all the blue cells (clues given to the user at the start)
// Placed into List for fast searching
private int iElement;
private boolean blShowResult; // Indicates if the user has clicked Show Result
private boolean blGiveHint; // Indicates if the user has clicked Give Hint
private boolean blSoundOn;
// UI Elements
private View tvCell;
private GridView gridView;
private Menu menu;
private MediaPlayer mp = null;
/* Lists
lstitems holds all the items in the current board including user entries
lstExclude holds all the blue cells (clues given to the user at the start)
adapter
*/
private List<String> lstItems;
private ArrayAdapter<String> adapter ;
private List<Integer> lstExcluded;
public MainActivity() {
stResult = new String[iMaxCells];
blGiveHint = false;
blShowResult = false;
iElement = 0;
blSoundOn = false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Declare used buttons
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
Button btn8 = (Button) findViewById(R.id.btn8);
Button btn9 = (Button) findViewById(R.id.btn9);
Button btn0 = (Button) findViewById(R.id.btn0);
Button btnHint = (Button) findViewById(R.id.btnHint);
Button btnCheck = (Button) findViewById(R.id.btnCheck);
//Creates a new Game
clsSudoku = new SudokuPuzzle();
newGame();
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
if (blGiveHint == true){
blGiveHint = false;
//Initialise any hinted cells back to white
clearCells();
}
if (!blShowResult){
tvCell = gridView.getChildAt(iElement);
try{
tvCell.setBackgroundColor(Color.WHITE);
iElement = position;
tvCell = gridView.getChildAt(iElement);
tvCell.setBackgroundColor(Color.RED);
}
catch(Exception e){
}
}
}
});
gridView.setAdapter(adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, lstItems) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setPadding(dpToPx(0, parent), 0, 0, 0);
view.setMinimumHeight(0);
if (position == iElement && !blShowResult){
view.setBackgroundColor(Color.RED);
}
else if (lstExcluded.contains(position)) {
view.setBackgroundColor(Color.WHITE);
}
else{
view.setBackgroundColor(Color.CYAN);
}
return view;
}
#Override
public boolean isEnabled(int position) {
// Item position which you want to disable.
if (!lstExcluded.contains(position) ) {
return false;
}
else {
return true;
}
}
});
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "1");
adapter.notifyDataSetChanged();
}
}
});
btn2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "2");
adapter.notifyDataSetChanged();
}
}
});
btn3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "3");
adapter.notifyDataSetChanged();
}
}
});
btn4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "4");
adapter.notifyDataSetChanged();
}
}
});
btn5.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "5");
adapter.notifyDataSetChanged();
}
}
});
btn6.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "6");
adapter.notifyDataSetChanged();
}
}
});
btn7.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "7");
adapter.notifyDataSetChanged();
}
}
});
btn8.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "8");
adapter.notifyDataSetChanged();
}
}
});
btn9.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "9");
adapter.notifyDataSetChanged();
}
}
});
btn0.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "");
adapter.notifyDataSetChanged();
}
}
});
btnHint.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
blGiveHint = true;
giveHint();
}
});
btnCheck.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkCorrect();
}
});
}
#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);
this.menu = 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
switch(id){
case R.id.new_game:
createNewGame();
return true;
case R.id.show_result:
getResult();
return true;
case R.id.sound_toggle:
setSoundSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Populate a list for fast searching later
private void populateExcludeList(int[] ipiArray){
lstExcluded.clear();
for (int iCnt = 0; iCnt < ipiArray.length; iCnt++){
lstExcluded.add(ipiArray[iCnt] - 1);
}
Collections.sort(lstExcluded);
}
// Populate a list for fast searching later
private void setBoard(String[] ipstArray){
lstItems.clear();
for (int iCnt = 0; iCnt < ipstArray.length; iCnt++){
lstItems.add(ipstArray[iCnt]);
}
}
// Create a new puzzle
private void newGame(){
String[] stNumbers = new String[iMaxCells];
blShowResult = false;
clsSudoku.swapTwoNumbers();
clsSudoku.swapTwoColumns();
clsSudoku.swapTwoBlocks();
clsSudoku.rotateNintyDegrees();
clsSudoku.clearNumbers();
stNumbers = clsSudoku.getResult("User");
stResult = clsSudoku.getResult("Result");
iExcluded = clsSudoku.getRemoved();
if (lstItems == null) {
lstItems = new ArrayList<String>(Arrays.asList(stNumbers));
}
else {
setBoard(stNumbers);
}
lstExcluded = new ArrayList<Integer>();
populateExcludeList(iExcluded);
iElement = lstExcluded.get(0);
}
private void createNewGame(){
if ( !lstItems.isEmpty() ){
lstItems.clear();
}
newGame();
adapter.notifyDataSetChanged();
}
private void getResult(){
blShowResult = true;
setBoard(stResult);
lstExcluded = new ArrayList<Integer>();
populateExcludeList(iExcluded);
adapter.notifyDataSetChanged();
}
public void giveHint(){
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
tvCell = gridView.getChildAt(iCnt);
try{
if (lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) == false && blGiveHint == true){
tvCell.setBackgroundColor(Color.RED);
}
else if(lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) && lstExcluded.contains(iCnt) ){
tvCell.setBackgroundColor(Color.WHITE);
}
}
catch(Exception e){
Toast.makeText(this, "Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
public void checkCorrect(){
boolean blErrorFound = false;
int iCntErrors = 0;
int iCntBlanks = 0;
String stMessage = "";
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
if ( (lstItems.get(iCnt).equalsIgnoreCase("") == true)
){
iCntBlanks = iCntBlanks + 1;
blErrorFound = true;
}
else if((lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) == false) &&
(lstItems.get(iCnt).equalsIgnoreCase("") == false)
){
iCntErrors = iCntErrors + 1;
blErrorFound = true;
}
}
if (!blErrorFound){
stMessage = "Congratulations !!! Your solution is correct";
if (blSoundOn == true){
playSound("congratulations");
}
}
else{
stMessage = "You have " + iCntErrors + " errors and " + iCntBlanks + " squares left to do";
if (blSoundOn == true){
playSound("wrong");
}
}
Toast.makeText(getApplicationContext(), stMessage, Toast.LENGTH_LONG).show();
}
private void clearCells(){
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
tvCell = gridView.getChildAt(iCnt);
if(lstExcluded.contains(iCnt) ){
tvCell.setBackgroundColor(Color.WHITE);
}
}
}
private void setSoundSettings() {
MenuItem miMenu = menu.findItem(R.id.sound_toggle);
if (blSoundOn) {
blSoundOn = false;
miMenu.setTitle("Turn Sound On");
} else {
blSoundOn = true ;
miMenu.setTitle("Turn Sound Off");
}
}
public void playSound(String stFileName){
int iSoundId;
if (mp != null){
mp.reset();
mp.release();
}
Resources res = getApplicationContext().getResources();
iSoundId = res.getIdentifier(stFileName, "raw", getApplicationContext().getPackageName());
mp = MediaPlayer.create(getApplicationContext(), iSoundId);
mp.start();
}
public int dpToPx(int dp, View v) {
DisplayMetrics displayMetrics = v.getContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
}

selected Image button changes its position in recyclerView when scrolling

i have a recyclerview in my MainActivity and i'm showing no of items in list manner through RecyclerView.Adapter. here is my recyclerview_list_items.xml file,
<?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:orientation="vertical"
android:padding="10dp">
<ImageView
android:id="#+id/person_photo"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
android:src="#drawable/rounded_img" />
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btnfollow"
android:layout_toRightOf="#+id/person_photo"
android:ellipsize="end"
android:paddingLeft="10dp"
android:paddingRight="4dp"
android:singleLine="true"
android:text="*********"
android:textColor="#303030"
android:textSize="17sp" />
<ImageButton
android:id="#+id/btnfollow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
android:background="#drawable/follow_inactive" />
</RelativeLayout>
and here is my adapter class file,
public class SuggestionListItemAdapter extends RecyclerView.Adapter<SuggestionListItemAdapter.MyViewHolder> {
private List<MovieData> moviesList;
Context context;
private boolean isButtonClicked = false;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView person_name;
ImageView person_photo;
ImageButton person_follow;
public MyViewHolder(View view) {
super(view);
person_photo = (ImageView) view.findViewById(R.id.person_photo);
person_name = (TextView) view.findViewById(R.id.person_name);
person_follow = (ImageButton) view.findViewById(R.id.btnfollow);
}
}
public SuggestionListItemAdapter(Context mContext,List<MovieData> moviesList) {
this.moviesList = moviesList;
this.context=mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_list_items, parent, false);
MyViewHolder viewHolder = new MyViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MovieData movieData = moviesList.get(position);
holder.person_name.setText(movieData.getGenre());
holder.person_photo.setImageResource(movieData.getPhoto());
holder.person_follow.setOnClickListener(clickListener);
holder.person_follow.setTag(holder);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnfollow) {
isButtonClicked = !isButtonClicked; // toggle the boolean flag
v.setBackgroundResource(isButtonClicked ? R.drawable.following_img : R.drawable.follow_inactive);
}
}
};
#Override
public int getItemCount() {
return moviesList.size();
}
}
Clicking on holder.person_follow image button , image drawable bg is changing accordingly what i want but when i am scrolling the page at that time image drawable bg changing its position automatically. for ex. if i select the image button pos=1, after scrolling the page its changes the selected button position.
Instead of placing isButtonClicked in adapter class place it in MovieData modal class.Then make following changes in your adapter class:
public class SuggestionListItemAdapter extends RecyclerView.Adapter<SuggestionListItemAdapter.MyViewHolder> {
private List<MovieData> moviesList;
Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView person_name;
ImageView person_photo;
ImageButton person_follow;
public MyViewHolder(View view) {
super(view);
person_photo = (ImageView) view.findViewById(R.id.person_photo);
person_name = (TextView) view.findViewById(R.id.person_name);
person_follow = (ImageButton) view.findViewById(R.id.btnfollow);
}
}
public SuggestionListItemAdapter(Context mContext,List<MovieData> moviesList) {
this.moviesList = moviesList;
this.context=mContext;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerview_list_items, parent, false);
MyViewHolder viewHolder = new MyViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final MovieData movieData = moviesList.get(position);
holder.person_name.setText(movieData.getGenre());
holder.person_photo.setImageResource(movieData.getPhoto());
holder.person_follow.setBackgroundResource(movieData.isButtonClicked() ? R.drawable.following_img : R.drawable.follow_inactive);
holder.person_follow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movieData.setIsButtonClicked(!movieData.isButtonClicked());
holder.person_follow.setBackgroundResource(movieData.isButtonClicked() ? R.drawable.following_img : R.drawable.follow_inactive);
}
});
holder.person_follow.setTag(holder);
}
#Override
public int getItemCount() {
return moviesList.size();
}
}

How to add a widget to a ListView to scroll with items, but also be visible when the ListView's adapter is empty

I have a ListView and a widget. I want the widget to be always on the top of ListView, and it should be able to scroll with the items but when there is no items in adapter it should still be visible. This is how it doesn't scroll:
The layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="#+id/btn_togle_empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="toggle empty"
/>
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="#+id/list_test"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<ViewStub
android:id="#+id/empty_layout"
android:layout="#layout/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>
</LinearLayout>
The code for the activity:
public class MyActivity extends Activity {
private MyAdapter adapter;
private ListView v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
v = (ListView) findViewById(R.id.list_test);
View empty = findViewById(R.id.empty_layout);
v.setEmptyView(empty);
final MyAdapter adapter = new MyAdapter();
v.setAdapter(adapter);
Button btn = (Button) findViewById(R.id.btn_togle_empty);
btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
adapter.togleEmpty();
}
});
}
private class MyAdapter extends BaseAdapter {
boolean empty = false;
#Override
public int getCount() {
return empty ? 0 : 50;
}
#Override
public Object getItem(int i) {
return new Object();
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
TextView v = new TextView(MyActivity.this);
v.setText("STRING");
return v;
}
public void togleEmpty() {
empty = !empty;
notifyDataSetChanged();
}
}
}
I had one more idea, add the widget as header, but it disappears when the ListView is empty. How can I achieve the result I want?
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (i == 0) { return custom_widget_view; }
}

Resources