Can't enable contextual action mode with CustomAdapter<MyClass> - java

I'm trying to enable contextual action mode in a ListView with my custom adapter inherited from ArrayAdapter<MyClass>. And can't. Just nothing is happening on long click. Neither in UI, nor in logs.
When I use ArrayAdapter<String> everything's working right. What is my mistake, please explain me. Thanks in advance.
Here are my files.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final String TAG = "LOG";
ListView listView;
ArrayAdapter<Note> adapter; // It doesn't work.
//ArrayAdapter<String> adapter; // It works.
List<Note> notes;
static final int REQUEST_CODE_NOTE = 1;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(android.R.id.list);
notes = new ArrayList<>();
notes.add(new Note("First note"), new Note("Second note"));
adapter = new NoteAdapter(this, notes);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
Log.d(MainActivity.TAG, "onCreateActionMode");
MenuInflater inflater = actionMode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
Toast.makeText(MainActivity.this, "onCreateActionMode", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
actionMode.finish();
return true;
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
}
});
//registerForContextMenu(listView);
btnAdd = (Button) findViewById(R.id.add_button);
btnAdd.setOnClickListener(this);
}
}
NoteAdapter.java
class NoteAdapter extends ArrayAdapter<Note> {
private AppCompatActivity parentActivity;
NoteAdapter(Context context, List<Note> notes) {
super(context, R.layout.note_item, notes);
this.parentActivity = (AppCompatActivity) context;
}
#NonNull
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final Note note = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.note_item, parent, false);
convertView.setLongClickable(true);
}
((TextView) convertView.findViewById(R.id.note)).setText(note.getText());
((TextView) convertView.findViewById(R.id.date_last_edited)).setText(note.getFormattedDate());
return convertView;
}
}
Note.java
class Note {
private String note;
private Calendar date_last_edited;
Note(String note) {
this.note = note;
this.date_last_edited = Calendar.getInstance();
}
Note(String note, Calendar date) {
this.note = note;
this.date_last_edited = date;
}
void setText(String text) {
this.note = text;
this.date_last_edited = Calendar.getInstance();
}
String getText() {
return this.note;
}
Calendar getDate() {
return this.date_last_edited;
}
String getFormattedDate() {
SimpleDateFormat formattedDate= new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return "Last edited: " + formattedDate.format(date_last_edited.getTime());
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="0dp"
android:paddingStart="0dp"
android:paddingRight="0dp"
android:paddingEnd="0dp"
android:paddingTop="0dp"
android:background="#color/colorBackground">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginTop="2dp"
android:id="#+id/add_button"
android:text="#string/add_button"
android:background="#drawable/button_background"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/add_button"
android:padding="0dp"
android:layout_marginLeft="2dp"
android:layout_marginStart="2dp"
android:layout_marginRight="2dp"
android:layout_marginEnd="2dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="0dp"
android:divider="#android:color/transparent"
android:dividerHeight="6dp"/>
</RelativeLayout>
note_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/note_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/note_margin"
android:paddingLeft="#dimen/note_margin"
android:paddingRight="#dimen/note_margin"
android:paddingTop="#dimen/note_margin"
android:background="?android:attr/activatedBackgroundIndicator"
android:clickable="true"
android:focusable="true"
android:longClickable="true"
tools:context="ru.geekbrains.lesson7.simplenotes.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:padding="10dp"
android:id="#+id/note"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Test note"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/note"
android:layout_alignParentBottom="true"
android:padding="10dp"
android:id="#+id/bottom_panel" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/date_last_edited"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Date: 01.01.2017 12:33:21"/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="#+id/delete_button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:contentDescription="Delete note"
android:src="#drawable/delete"/>
<ImageView
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:id="#+id/edit_button"
android:layout_toLeftOf="#id/delete_button"
android:layout_toStartOf="#id/delete_button"
android:contentDescription="Edit note"
android:src="#drawable/edit"/>
</RelativeLayout>
</RelativeLayout>
context_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title="#string/delete_all_context_menu"
android:id="#+id/delete_all_context"
android:icon="#android:drawable/ic_menu_delete">
</item>
</menu>

Related

inputData to send data to mainActivity error using Realm Database instant crash

I have a problem that when I press the Fab button the app instant close and I don't know how to fix it, my goal was when pressing the fab button and inserting the data it will send the data to the MainActivity.xml and make a list of item
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expenses"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Balance"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="0"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
<ListView
android:id="#+id/listView"
app:layout_anchor="#id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp">
</ListView>
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabCradleMargin="10dp"
app:fabCradleVerticalOffset="10dp"
app:fabCradleRoundedCornerRadius="20dp"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottomNavigationView"
app:menu="#menu/bottom_nav_menu"
android:layout_marginEnd="10dp"/>
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/fab"
android:src="#drawable/add_button"
app:layout_anchor="#id/bottomAppBar"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
activity_input_data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".InputDataActivity">
<LinearLayout
android:layout_marginTop="200dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginBottom="200dp"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textAlignment="center"
android:textSize="50dp"
android:textStyle="bold"
android:text="Input Data"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtTitle"
android:hint="Title..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtAmount"
android:hint="Amount..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="#+id/txtDate"
android:hint="Date..."
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addButton"
android:text="Add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="20dp">
<ImageView
android:src="#drawable/profile_button"
android:layout_width="50dp"
android:layout_height="50dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/title"
android:layout_gravity="end"
android:textSize="16dp"
android:textStyle="bold"
android:text="Main Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/amount"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Rp. 20.000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/date"
android:layout_gravity="end"
android:textSize="12dp"
android:textStyle="bold"
android:text="23-06-2021"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/spinner"
android:layout_gravity="end"
android:textSize="14dp"
android:textStyle="bold"
android:text="Expense"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
MyHelper myHelper;
BottomNavigationView bottomNavigationView;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
floatingActionButton = findViewById(R.id.fab);
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, InputDataActivity.class);
startActivity(intent);
}
});
//Bottom Nav
bottomNavigationView.setBackground(null);
bottomNavigationView.getMenu().getItem(2).setEnabled(false);
}
}
InputDataActivity.java
public class InputDataActivity extends AppCompatActivity {
EditText txtTitle, txtAmount,txtDate;
Button button;
Realm realm;
ListView listView;
MyHelper myHelper;
RealmChangeListener realmChangeListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_data);
realm = Realm.getDefaultInstance();
txtTitle = findViewById(R.id.txtTitle);
txtAmount = findViewById(R.id.txtAmount);
txtDate = findViewById(R.id.txtDate);
button = findViewById(R.id.addButton);
listView = findViewById(R.id.listView);
//MyHelper
myHelper = new MyHelper(realm);
myHelper.selectFromDB();
//ListView Adapter
ListViewAdapter adapter = new ListViewAdapter(this, myHelper.justRefresh());
listView.setAdapter(adapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Refresh();
}
private void saveData(){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Number maxId = realm.where(User.class).max("title_id");
int newKey = (maxId == null) ? 1 : maxId.intValue()+1;
User user = realm.createObject(User.class, newKey);
user.setTitle_name(txtTitle.getText().toString());
user.setAmount(txtAmount.getText().toString());
user.setDate(txtDate.getText().toString());
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(InputDataActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(InputDataActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
}
private void Refresh(){
realmChangeListener = new RealmChangeListener() {
#Override
public void onChange(Object o) {
ListViewAdapter adapter = new ListViewAdapter(InputDataActivity.this, myHelper.justRefresh());
listView.setAdapter(adapter);
}
};
realm.addChangeListener(realmChangeListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();
}
}
MyHelper.java
public class MyHelper {
Realm realm;
RealmResults<User> users;
public MyHelper(Realm realm) {
this.realm = realm;
}
public void selectFromDB(){
users = realm.where(User.class).findAll();
}
public ArrayList<User> justRefresh(){
ArrayList<User> listItem = new ArrayList<>();
for(User user: users){
listItem.add(user);
}
return listItem;
}
}
User.java
public class User extends RealmObject {
#PrimaryKey
private int title_id;
private String title_name;
private String amount;
private String date;
private String spinner;
public int getTitle_id() {
return title_id;
}
public void setTitle_id(int title_id) {
this.title_id = title_id;
}
public String getTitle_name() {
return title_name;
}
public void setTitle_name(String title_name) {
this.title_name = title_name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSpinner() {
return spinner;
}
public void setSpinner(String spinner) {
this.spinner = spinner;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
Context context;
ArrayList<User> users;
public ListViewAdapter(Context context, ArrayList<User> users) {
this.context = context;
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater =(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view =inflater.inflate(R.layout.list_item, parent,false);
TextView title,amount,date,spinner;
title =view.findViewById(R.id.title);
amount = view.findViewById(R.id.amount);
date = view.findViewById(R.id.date);
spinner = view.findViewById(R.id.spinner);
User u = (User)this.getItem(position);
title.setText(u.getTitle_name());
amount.setText(u.getAmount());
date.setText(u.getDate());
spinner.setText(u.getSpinner());
int numPosition = u.getTitle_id();
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// for update
}
});
return view;
}
}
if someone can help, Thank you because I'm stuck here. my goal is to make Money Management

Slide image with recyclerview in full screen android

I have created a wallpaper app where I'm loading images from the firebase database in recyclerview. When I click on recyclerview item(image) that item's image URL is sent to the next activity and then that URL is loaded into imageView using glide.
I want to change this to something like Image-Slider. By clicking on the recyclerView item I want to show that image in full screen and slide from left or right(next or previous). But I don't know how to do that.
Here is my code.
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
adapter = new FeaturedAdapter(list);
recyclerView.setAdapter(adapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Wallpaper All");
Query query = databaseReference.orderByChild("dark").equalTo(true);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
FeaturedModel model = dataSnapshot1.getValue(FeaturedModel.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e("TAG_DATABASE_ERROR", databaseError.getMessage());
}
});
FeaturedAdapter.java
public class FeaturedAdapter extends RecyclerView.Adapter<FeaturedAdapter.ViewHolder> {
private List<FeaturedModel> featuredModels;
public FeaturedAdapter(List<FeaturedModel> featuredModels) {
this.featuredModels = featuredModels;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_image, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(featuredModels.get(position).getImageLink()
, position,
featuredModels.get(position).isPremium());
}
#Override
public int getItemCount() {
return featuredModels.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private ImageView premiumImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageview);
premiumImage = itemView.findViewById(R.id.premium);
}
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), PremiumViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), ViewActivity.class);
//setIntent.putExtra("title", url);
setIntent.putExtra("images", featuredModels.get(getAdapterPosition()).getImageLink());
setIntent.putExtra("id", featuredModels.get(position).getId());
itemView.getContext().startActivity(setIntent);
}
});
}
}
}
}
ViewActivity
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
relativeLayout.setBackgroundColor(color);
Glide.with(this)
.load(getIntent().getStringExtra("images"))
.timeout(6000)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(imageView);
setBackgroundWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setBackgroundImage();
}
});
}
private void setBackgroundImage() {
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
WallpaperManager manager = WallpaperManager.getInstance(getApplicationContext());
try {
manager.setBitmap(bitmap);
Toasty.success(getApplicationContext(), "Set Wallpaper Successfully", Toast.LENGTH_SHORT, true).show();
} catch (IOException e) {
Toasty.warning(this, "Wallpaper not load yet!", Toast.LENGTH_SHORT, true).show();
}
}
activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".activity.PremiumViewActivity">
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#00BCD4"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/lottieSuccess"
android:layout_width="180dp"
android:layout_height="180dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:lottie_fileName="checked.json" />
<RelativeLayout
android:id="#+id/wallpaper_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent">
<ImageButton
android:id="#+id/saveImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:contentDescription="#null"
android:src="#drawable/save" />
<Button
android:id="#+id/setWallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="4dp"
android:layout_marginEnd="8dp"
android:background="#drawable/set_as_wallpaper_btn"
android:minWidth="230dp"
android:text="Set as wallpaper"
android:textColor="#000"
android:textStyle="bold" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:orientation="horizontal">
<CheckBox
android:id="#+id/favoritesBtn_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:button="#drawable/favourite_checkbox_selector" />
<ImageButton
android:id="#+id/shareBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="6dp"
android:background="#drawable/share"
android:contentDescription="#null" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/ads_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent">
<Button
android:id="#+id/watch_ads"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/advertizing"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Watch Video Ad"
android:textColor="#000"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/watch_ads">
<Button
android:id="#+id/unlock_withCoins"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="20dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="20dp"
android:background="#drawable/set_as_wallpaper_btn"
android:drawableStart="#drawable/diamond"
android:paddingStart="50dp"
android:paddingEnd="50dp"
android:stateListAnimator="#null"
android:text="Unlock with diamonds"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/diamonds_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:gravity="center"
android:text="Total Diamonds: 0"
android:textSize="10sp"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
custom_image.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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:background="#fff"
app:cardCornerRadius="10dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#null"
android:scaleType="centerCrop"
android:src="#color/colorPrimary" />
<ImageView
android:id="#+id/premium"
android:contentDescription="#null"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_margin="10dp"
app:srcCompat="#drawable/diamond" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
Structure
MainActivity
|
| //Click button to open
|
FragActivity
|
| //FrameLayout
|
Fragment
|
| //here is the recyclerView
| //Open new Activity to view image
ViewActivity
Screen Recording
This can be solved by using ViewPager or ViewPager2 in Android
First create an Adapter
ImageSwiperAdapter2.java
public class ImageSwiperAdapter2 extends RecyclerView.Adapter<ImageSwiperAdapter2.ImageSwiper> {
private List<FeaturedModel> list;
private Context context;
public ImageSwiperAdapter2(List<FeaturedModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public ImageSwiper onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.slidingimages,
parent, false);
return new ImageSwiper(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageSwiper holder, int position) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
holder.relativeLayout.setBackgroundColor(color);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageLink())
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
holder.relativeLayout.setBackgroundColor(Color.TRANSPARENT);
return false;
}
})
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
class ImageSwiper extends RecyclerView.ViewHolder {
private ImageView imageView;
public ImageSwiper(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
In ViewActivity/SwiperActivity.java
public class SwiperActivity extends AppCompatActivity {
private ViewPager2 viewPager;
private List<FeaturedModel> list;
private ImageSwiperAdapter2 adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swiper);
viewPager = findViewById(R.id.view_pager);
final int pos = getIntent().getIntExtra("pos", 0);
Singleton singleton = Singleton.getInstance();
list = new ArrayList<>();
list = singleton.getListSin();
adapter2 = new ImageSwiperAdapter2(list, this);
viewPager.setAdapter(adapter2);
viewPager.setCurrentItem(pos);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
Toast.makeText(SwiperActivity.this, "Selected: " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
}
You can pass the list and clicked item position in FeaturedAdapter.
In your FeaturedAdapter's setData method
private void setData(final String url, final int position, boolean premium) {
Glide.with(itemView.getContext().getApplicationContext()).load(url).into(imageView);
final Singleton a = Singleton.getInstance();
a.setListSin(featuredModels);
if (premium) {
premiumImage.setVisibility(View.VISIBLE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
} else {
premiumImage.setVisibility(View.GONE);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent setIntent = new Intent(itemView.getContext(), SwiperActivity.class);
setIntent.putExtra("pos", position);
itemView.getContext().startActivity(setIntent);
CustomIntent.customType(itemView.getContext(), "fadein-to-fadeout");
}
});
}
}
slidingimages.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">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#null"
android:scaleType="centerCrop" />
</RelativeLayout>
activity_swiper.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"
tools:context=".SwiperActivity">
<androidx.viewpager2.widget.ViewPager2
android:orientation="horizontal"
android:id="#+id/view_pager"
android:layoutDirection="inherit"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Since the ViewActivity must show all the images(when slided) it must contain the adapter with the set of image urls.
Instead of using an ImageView, use a RecyclerView in the ViewActivity and attach the adapter. In your code, do the following to make the recycler view horizontal and add slide functionality.
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);
Few Days ago, I had been looking for similar requirement for showing slid-able image View.
This situation can be solved using ViewPager in Android.
You can use following Tutorials for building such Slide Image View using ViewPager
Java Resources
Blog Tutorial
Video Tutorial
Kotlin Resources
Video Tutorial

Why does my scrollview leave "shadows" behind?

So I am developing an app that uses firebase to load a list of buses, and if they have arrived or not. I'm relatively new to this and am trying to use fragments. I can get the fragment to load in successfully with the list of buses, but when I scroll through them it leaves behind a copy of the items, as seen here:
When it loads
When I scroll
MainActivity:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(null);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
BusFragment busFragment = new BusFragment();
transaction.add(R.id.buscontainer, busFragment);
transaction.commit();
}
#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;
}
MainActivity xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.jackheinemann.schoolbus.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:layout_width="match_parent"
android:layout_height="64dp"/>
<FrameLayout
android:id="#+id/buscontainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom">
</FrameLayout>
</LinearLayout>
BusFragment:
public class BusFragment extends Fragment {
public boolean isInitialized = false;
// Database Instance Variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mBusref;
private ChildEventListener mChildEventListener;
// Tablerow ID's
final Integer[] tableRows = {R.id.tablerow1, R.id.tablerow2, R.id.tablerow3,
R.id.tablerow4, R.id.tablerow5, R.id.tablerow6, R.id.tablerow7, R.id.tablerow8,
R.id.tablerow9, R.id.tablerow10, R.id.tablerow11, R.id.tablerow12,
R.id.tablerow13, R.id.tablerow14, R.id.tablerow15};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View busView = inflater.inflate(R.layout.activity_bus_fragment, container, false);
onSignedInInitialize();
init();
return busView;
}
public void onSignedInInitialize() {
if (mChildEventListener == null) {
mFirebaseDatabase = FirebaseDatabase.getInstance();
mBusref = mFirebaseDatabase.getReference().child("buses");
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String bus_name = dataSnapshot.getKey();
Boolean bus_loc = dataSnapshot.getValue(Boolean.class);
String bus_location = Boolean.toString(bus_loc);
Integer findview = grabBusNumber(bus_name);
TextView textView = (TextView) getView().findViewById(findview);
textView.setText(bus_location);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mBusref.addChildEventListener(mChildEventListener);
}
}
public void init() {
mBusref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i = 1;
View view = getView();
for (DataSnapshot buslist : dataSnapshot.getChildren()) {
if (i < 16) {
String bus = "Bus " + Integer.toString(i);
Boolean location = buslist.getValue(Boolean.class);
TextView bus_name = new TextView(getActivity());
TextView bus_location = new TextView(getActivity());
TableRow.LayoutParams params = new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 1f);
bus_name.setText(bus);
bus_name.setTextSize(30);
bus_name.setLayoutParams(params);
bus_name.setGravity(Gravity.CENTER);
bus_location.setText(Boolean.toString(location));
bus_location.setTextSize(30);
bus_location.setLayoutParams(params);
bus_location.setGravity(Gravity.CENTER);
Integer identifier = i;
bus_location.setId(identifier);
if (view != null) {
TableRow tableRow = (TableRow) view.findViewById(tableRows[i - 1]);
tableRow.addView(bus_name);
tableRow.addView(bus_location);
i++;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
isInitialized = true;
}
private Integer grabBusNumber(String bus_id) {
String string;
if (bus_id.charAt(1) != '_') {
string = Character.toString(bus_id.charAt(0)) + Character.toString(bus_id.charAt(1));
} else {
string = Character.toString(bus_id.charAt(0));
}
Integer integer = Integer.parseInt(string);
return integer;
}
}
activity_bus_fragment.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_bus_fragment"
android:orientation="vertical"
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"
tools:context="com.jackheinemann.schoolbus.BusFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="#+id/tablerow1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow3"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow4"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow5"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow6"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow7"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow8"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow9"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow10"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow11"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow12"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow13"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow14"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:id="#+id/tablerow15"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</TableLayout>
</ScrollView>
</LinearLayout>
For anyone here looking for an answer, the way I fixed the issue was changing the fragment additions to fragment replacements. For some reason it was adding the fragments twice, hence the "shadows". Replacing instead of adding ensured there was only one loaded and fixed the issue.

setOnClickListener not firing with custom adapter and custom ListView

I've been spending a few hours on a problem and I still can't figure it out. The setOnClickListener in HotelOverviewFragment is not firing when I click an item in my ListView. However, the setOnClickListener does work from my custom adapter (NowArrayAdapter).
My question is: why the setOnClickListener not working in HotelOverviewFragment (Class where the ListView is shown)?
Here's a list of what I've tried:
Setting android:focusable="false", android:focusableInTouchMode="false", android:descendantFocusability="blocksDescendants" in the hotel_row_layout.xml and fragment_hotel_overview.xml.
Setting android:clickable on true and false. Both didn't work.
Changing from BaseAdapter implementation to arrayAdapter.
I tried different listeners in HotelOverviewFragment: setOnClickListener, setOnItemClickListener, setOnItemSelectedListener and setOnTouchListener. Unfortunately, none of those worked for me.
Here's my code:
Custom adapter
public class NowArrayAdapter extends ArrayAdapter<String> {
private Context context;
private ArrayList<String> values;
private Typeface typeface;
private static Hashtable fontCache = new Hashtable();
private LayoutInflater inflater;
private TextView item;
public NowArrayAdapter(Context context, ArrayList<String> commandsList) {
super(context, R.layout.hotel_row_layout, commandsList);
this.context = context;
values = new ArrayList<String>();
values.addAll(commandsList);
typeface = getTypeface(this.context, "fonts/Roboto-Light.ttf");
inflater = LayoutInflater.from(this.context);
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public View getView(int position, View convertView, ViewGroup parent) {
String myText = getItem(position);
if(convertView == null) {
convertView = inflater.inflate(R.layout.hotel_row_layout, parent, false);
item = (TextView) convertView.findViewById(R.id.maps_button);
item.setTypeface(typeface);
convertView.setTag(item);
} else {
item = (TextView) convertView.getTag();
}
item.setText(myText);
//myListItem.descText.setTextSize(14);
convertView.setOnClickListener(new View.OnClickListener() {
// WORKS!
#Override
public void onClick(View view) {
Log.d("click", "Don't look at me!");
}
});
return convertView;
}
}
Fragment
public class HotelOverviewFragment extends Fragment {
private static Hashtable fontCache = new Hashtable();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_hotel_overview, container, false);
ListView list = (ListView) v.findViewById(android.R.id.list);
// Set up listview and buttons
setUp(v, list);
// Inflate the layout for this fragment
return v;
}
static Typeface getTypeface(Context context, String font) {
Typeface typeface = (Typeface)fontCache.get(font);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), font);
fontCache.put(font, typeface);
}
return typeface;
}
public void setUp(View v, ListView l){
TextView address = (TextView) v.findViewById(R.id.content);
TextView header = (TextView) v.findViewById(R.id.header);
TextView hotelName = (TextView) v.findViewById(R.id.hotelName);
Typeface typeface = getTypeface(getActivity(), "fonts/Roboto-Light.ttf");
address.setText("some street \nZipCode, City \nCountry \nEmail \nphoneNumber");
address.setTypeface(typeface);
header.setText("Hotel info");
header.setTypeface(typeface);
header.setTextSize(20);
hotelName.setText("Hotel name");
hotelName.setTypeface(typeface);
// Set up button
ArrayList<String> n = new ArrayList<String>();
n.add(0, "More info");
// Show button
NowArrayAdapter adapter = new NowArrayAdapter(getActivity(), n);
l.setAdapter(adapter);
// THIS IS THE STUFF I'VE BEEN TRYING
try {
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("click", "Success");
}
});
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
});
l.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("click", "Success");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
l.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("click", "Success");
return false;
}
});
}catch (Exception e){
Log.d("click", e + "");
}
}
}
Layout xml of HotelOverviewFragment
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.example"
android:background="#ffebebeb">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="200dp"
android:src="#drawable/banner"
android:id="#+id/hotelBanner"
android:layout_gravity="top"
android:adjustViewBounds="false"
android:scaleType="fitXY" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Hotelname"
android:id="#+id/hotelName"
android:gravity="center"
android:textSize="40dp"
android:layout_alignBottom="#+id/hotelBanner"
android:layout_alignParentRight="false"
android:layout_alignParentLeft="false"
android:textColor="#ffc4c4c4"
android:layout_marginBottom="5dp" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="0dp"
android:background="#drawable/header_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/header"
android:layout_gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Header"
android:layout_toRightOf="#+id/headerImage"
android:layout_centerVertical="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/headerImage"
android:src="#drawable/ic_action_live_help"
android:layout_centerVertical="true" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:background="#drawable/content_card">
<TextView
android:id="#+id/content"
android:layout_gravity="left|center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:text="Content"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:clickable="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
The custom xml for a listview item
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/content_card">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/maps_button"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
android:layout_weight="1"
android:textColor="#android:color/primary_text_light"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
<ImageView
android:src="#drawable/ic_action_arrow_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="false"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="false"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</LinearLayout>
Thanks in advance.
Thanks to Daniel Nugent's suggestion I got it working. Removing the convertView.setOnClickListener() is part of the answer. I think it was blocking the other listeners in the HotelOverviewFragment.
My next mistake was that I used setOnClickListener on a ListView for testing.
setOnClickListener should be used for buttons not ListViews.
So after removing setOnClickListener all the other listeners started working.
Thanks for your time.

i need to insert an image in my listview

I am new in android development and I need to modify my code to make it show the text with image function:
print_view xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BFAF80">
<ListView
style="14dp"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:id="#+id/operations"
android:layout_below="#+id/search_view"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_below="#+id/operations"
android:layout_centerHorizontal="true"
android:src="#drawable/printer" />
list_row_item xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:padding="20dp"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_weight="1"
android:src="#drawable/wifi"
android:layout_height="wrap_content"
android:id="#+id/imageForList" />
<TextView
android:layout_width="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginTop="35dp"
android:layout_height="wrap_content"
android:text="Nearby Wifi"
android:id="#+id/textForList" />
<ImageView
android:layout_width="match_parent"
android:layout_weight="1"
android:src="#drawable/bluetooth"
android:layout_height="wrap_content"
android:id="#+id/imageForList2" />
<TextView
android:layout_width="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginTop="35dp"
android:layout_height="wrap_content"
android:text="Nearby Blutooth"
android:id="#+id/textForList2" />
<ImageView
android:layout_width="match_parent"
android:layout_weight="1"
android:src="#drawable/usb"
android:layout_height="wrap_content"
android:id="#+id/imageForList3" />
<TextView
android:layout_width="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginTop="35dp"
android:layout_height="wrap_content"
android:text="Direct USB Connected"
android:id="#+id/textForList3" />
<ImageView
android:layout_width="match_parent"
android:layout_weight="1"
android:src="#drawable/cloud"
android:layout_height="wrap_content"
android:id="#+id/imageForList4" />
<TextView
android:layout_width="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginTop="35dp"
android:layout_height="wrap_content"
android:text="Google Cloud Print"
android:id="#+id/textForList4" />
</LinearLayout>
SettingsList java class:
public class SettingsList {
private int[] images;
private String[] items;
public SettingsList(int[] images, String[] items) {
this.images = images;
this.items = items;
}
public int[] getImages() {
return images;
}
public void setImages(int[] images) {
this.images = images;
}
public String[] getItems() {
return items;
}
public void setItems(String[] items) {
this.items = items;
}
}
SettingsAdapter java class :
public class SettingsAdapter extends ArrayAdapter<SettingsList> {
public SettingsAdapter(Context context, int resource, List<SettingsList> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItems holder;
if(convertView == null){
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_row_item, parent, false);
holder = new ViewHolderItems();
holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList);
holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList2);
holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList3);
holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList4);
holder.holderText = (TextView)convertView.findViewById(R.id.textForList);
holder.holderText = (TextView)convertView.findViewById(R.id.textForList2);
holder.holderText = (TextView)convertView.findViewById(R.id.textForList3);
holder.holderText = (TextView)convertView.findViewById(R.id.textForList4);
convertView.setTag(holder);
}else{
holder = (ViewHolderItems)convertView.getTag();
}
SettingsList current = getItem(position);
holder.holderImage.setImageResource(current.getImages()[position]);
holder.holderText.setText(current.getItems()[position]);
return convertView;
}
static class ViewHolderItems{
ImageView holderImage;
TextView holderText;
}
}
PrintView mainactivity :
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PrintView extends ActionBarActivity { private ListView lv;
private SettingsAdapter adapter;
private List<SettingsList> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.print_view);
int[] imgs = new int[]
{
R.drawable.wifi,
R.drawable.bluetooth,
R.drawable.usb,
R.drawable.cloud,
};
String[] values = new String[]
{"Nearby Wifi",
"Nearby Blutooth",
"Direct USB Connected",
"Google Cloud Print"
};
lv = (ListView)findViewById(R.id.operations);
itemList = new ArrayList<>();
itemList.add(new SettingsList(imgs, values));
adapter = new SettingsAdapter(PrintView.this, R.layout.list_row_item, itemList);
lv.setAdapter(adapter);
}
}
Try this:
1) Create a res/layout/list_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:padding="20dp"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_weight="1"
android:src="#mipmap/ic_launcher"
android:layout_height="wrap_content"
android:id="#+id/imageForList" />
<TextView
android:layout_width="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginTop="35dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textForList" />
</LinearLayout>
</LinearLayout>
2) Create your custom List item:
public class SettingsList {
private int image;
private String item;
public SettingsList(int image, String item) {
this.image = image;
this.item = item;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
3) Create your custom adapter
public class SettingsAdapter extends ArrayAdapter<SettingsList> {
public SettingsAdapter(Context context, int resource, List<SettingsList> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItems holder;
if(convertView == null){
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_row_item, parent, false);
holder = new ViewHolderItems();
holder.holderImage = (ImageView)convertView.findViewById(R.id.imageForList);
holder.holderText = (TextView)convertView.findViewById(R.id.textForList);
convertView.setTag(holder);
}else{
holder = (ViewHolderItems)convertView.getTag();
}
SettingsList current = getItem(position);
holder.holderImage.setImageResource(current.getImage());
holder.holderText.setText(current.getItem());
return convertView;
}
static class ViewHolderItems{
ImageView holderImage;
TextView holderText;
}
}
4) In your Activity that you want the listview to be shown do this:
public class YourActivity extends ActionBarActivity {
private ListView lv;
private SettingsAdapter adapter;
private List<SettingsList> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView)findViewById(R.id.operations);
itemList = new ArrayList<>();
itemList.add(new SettingsList(R.drawable.wifi, Nearby Wifi));
itemList.add(new SettingsList(R.drawable.bluetooth, Nearby Blutooth));
itemList.add(new SettingsList(R.drawable.usb, Direct USB Connected));
itemList.add(new SettingsList(R.drawable.cloud, Google Cloud Print));
adapter = new SettingsAdapter(YourActivity.this, R.layout.list_row_item, itemList);
lv.setAdapter(adapter);
}
}
5) The print_view.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#BFAF80">
<ListView
style="14dp"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:id="#+id/operations"
android:layout_below="#+id/search_view"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Hope it helps!!!

Categories