Android - How to get the currently "focused" object? - java

I want to let a Button identify which of my TextViews got the current focus. And after that the Button needs to apply changes to the focused TextView.
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
textView11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView11.setBackgroundColor(Color.LTGRAY);
textView11.setFocusableInTouchMode(true);
textView11.requestFocus();
}
});
MaterialButton pb1 = (MaterialButton) findViewById(R.id.pin_button_1);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//1. get the focused textview or scan for the focused textView
//2. apply button function to the focused textView
}
});
So how can i identify here
//1. get the focused textview or scan for the focused textView
which TextView has the focus currently?
I think it might be possible with some help variable but maybe there os another way, because then i still need a onClickListener for each of the 22 TextView

Untested but should work
private TextView hasFocusTextView;
private View.OnFocusChangeListener onFocusChangedListener = new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
hasFocusTextView = (TextView) v;
}
};
..
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
//Use same listener on all textview you want to include with the focus logic
textView11.setOnFocusChangeListener(onFocusChangedListener);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasFocusTextView.setText("Changing text of the focused TextView");
}
});

You can simply place these TextView in the same ViewGroup, then just traverse the ViewGroup's child views like this:
for (child in container.children){
if (child.isFocused){
//do your jobs here
}
}

Best way is to use a variable to store which TextView currently has focus.
TextView currentTextView = null;
void initView() {
TextView textView11 = (TextView) findViewById(R.id.frame1_1);
textView11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textView11.setBackgroundColor(Color.LTGRAY);
textView11.setFocusableInTouchMode(true);
textView11.requestFocus();
// Set the currentTextView to the currently focused
// this must be used in every focusable textview
currentTextView = (TextView) view;
}
});
MaterialButton pb1 = (MaterialButton) findViewById(R.id.pin_button_1);
pb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//1. get the focused textview or scan for the focused textView
// focused textview is currentTextView
//2. apply button function to the focused textView
// Edit: Check for nullability
if (currentTextView != null) {
// use the variable currentTextView
}
}
});
}

Related

RecyclerView how to setOnClickListener on every item?

What I want this code to do is: whenever the user clicks on the item (example: like or dislike),
I want something to happen to my firebase (eg. set the value of the like to 1).
I'm trying so hard to set a click listener for every item (like, dislike, happy emote, report).
Even if I set the click listener inside the static class, I can't call my Database Reference.
I also tried to do CommentsActivity.this.mReviewsDatabase..etc but it doesn't work because it doesn't want a static class. And if I remove the static from the class, the app crashes.
public class CommentsActivity extends AppCompatActivity {
private RecyclerView mCommentList;
public DatabaseReference mReviewsDatabase;
private FirebaseUser mCurrentUser;
private ImageView happyEmote, thumpUp, thumbDown ,reportReview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
String title = getIntent().getStringExtra("EXTRA_SESSION_ID");
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mReviewsDatabase = FirebaseDatabase.getInstance().getReference().child("Film_reviews").child(title);
mCommentList = (RecyclerView)findViewById(R.id.reviews_list);
mCommentList.setHasFixedSize(true);
mCommentList.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerAdapter<AllCommClass, CommentsActivity.ReviewsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AllCommClass, CommentsActivity.ReviewsViewHolder>(
AllCommClass.class,
R.layout.comment_single_layout,
CommentsActivity.ReviewsViewHolder.class,
mReviewsDatabase
) {
#Override
protected void populateViewHolder(CommentsActivity.ReviewsViewHolder reviewsViewHolder, AllCommClass allCommClass, int i) {
reviewsViewHolder.setUsername(allCommClass.getUsername());
reviewsViewHolder.setReview(allCommClass.getReview());
reviewsViewHolder.setVoto(allCommClass.getVoto());
reviewsViewHolder.setReport();
reviewsViewHolder.setLike();
reviewsViewHolder.setDislike();
reviewsViewHolder.setHappyEmote();
reviewsViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { }
});
}
};
mCommentList.setAdapter(firebaseRecyclerAdapter);
}
public static class ReviewsViewHolder extends RecyclerView.ViewHolder {
View mView;
public ReviewsViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setReport() {
ImageView reportReview = mView.findViewById(R.id.reportReview);
reportReview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Tag","You've reported the comment number "+getAdapterPosition());
}
});
}
public void setLike() {
ImageView thumpUp = mView.findViewById(R.id.thumbUp);
thumpUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Tag","You've liked the comment number "+getAdapterPosition());
}
});
}
public void setDislike() {
ImageView thumpDown = mView.findViewById(R.id.thumbDown);
thumpDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Tag","You've disliked the comment number "+getAdapterPosition());
}
});
}
public void setHappyEmote() {
ImageView happyEmote = mView.findViewById(R.id.happyEmote);
happyEmote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Tag","You've added a reaction to the comment number "+getAdapterPosition());
}
});
}
public void setUsername(String username){
TextView titleView = mView.findViewById(R.id.user_single_username_comment_section);
titleView.setText(username);
}
public void setReview(String review){
TextView titleView = mView.findViewById(R.id.user_single_review);
titleView.setText(review);
}
public void setVoto(int voto){
TextView titleView = mView.findViewById(R.id.user_single_rating);
titleView.setText(String.valueOf(voto));
}
}}
"
There are basically 2 ways as a beginner to set click listener to a recycler view item.
The first was is the easy but nonoptimal way to do it. Inside your onBindViewHolder of your adapter class set an onClickListener to your holder.itemview
The second way is to use an onClickInterface and then call it from the calling/main activity. Please let me know if you need any further guidance
When we are fetching data from firebase
The process is to match the Id of the item on firebase you are fetching through your model class to populate your recycleView.
If you want your application to remember the number of like or dislike on a certain button you need to set count on the id of the item on which the user will perform the click.
You can show that count or keep track of the button click in that manner.
If you need the code for it let me know

How to Concatenate Multiple Textviews Which are One Word Just Like All TextViews (Words) are Merged as Paragraph

I have multiple textviews. And all textviews are one word. I want to build a paragraph by using them. But they should not lose their textview feature. So they should not be used as string. Because then, I want them to be clickable one by one.
You can use a single textview and spannable string to make the words clickable separately.
TextView textview1,textview2,textview3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
textview1 = findViewById(R.id.textview1);
textview2 = findViewById(R.id.textview2);
textview3 = findViewById(R.id.textview3);
textview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
}
});
textview2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
}
});
textview3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
}
});
}

How to remove added views programmatically

I have a dialog wherein a user can add EditText and also remove it. I have successfully added EditText programmatically but my code for removing it doesn't work. I'm following this tutorial but in my case setup is inside a dialog.
and also i want to get all the the texts on those EditTexts and store it inside an Array.
This is my code:
public void showSurveyDialog(Context context) {
ImageButton btnAddChoices, btnRemoveChoice;
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.survey_content);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
btnAddChoices = dialog.findViewById(R.id.btn_add_choices);
LinearLayout choiceLayout = dialog.findViewById(R.id.choice_layout);
btnAddChoices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = dialog.getLayoutInflater().inflate(R.layout.choice_item, null);
// Add the new row before the add field button.
choiceLayout.addView(rowView, choiceLayout.getChildCount() - 1);
ImageButton imageButton = dialog.findViewById(R.id.btn_choice_close);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("asdass","ASDASd");
choiceLayout.removeView((View)v.getParent());
}
});
}
});
dialog.show();
}
When pressing btnAddChoices a layout with EditText and Button(for removing) is automatically added to a linear layout. I'am trying to make the remove button to work but it doesn't remove the view.
you can try my add and remove code for references, this can add or remove view programmatically:
private void addressField(View view){
final int[] textCount = {0};
LinearLayout addressLayout = view.findViewById(R.id.address_layout);
addressScroll.removeView(addressLayout);
View layout2 = LayoutInflater.from(view.getContext()).inflate(R.layout.address_text_field
, addressLayout,false);
layout2.setTag("address"+Integer.toString(counter));
addressLayout.addView(layout2);
addressScroll.addView(addressLayout);
ImageView deleteButton = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.delete_address);
TextFieldBoxes addressText = layout2.findViewWithTag("address"+Integer.toString(counter))
.findViewById(R.id.address_wrapper);
addressText.setSimpleTextChangeWatcher((theNewText, isError) -> {
if(Objects.equals(theNewText, "")){
textCount[0] = 0;
addressLayout.removeView(layout2);
}
if(theNewText.length() == 1 && textCount[0] == 0){
addressField(view);
ExtendedEditText addressText2 = layout2.findViewWithTag("address"+Integer.toString(counter-1))
.findViewById(R.id.address_text);
addressText2.requestFocus();
counter++;
}
textCount[0]++;
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addressLayout.removeView(layout2);
}
});
}
hope can solve your problems

TextSwitcherActivity, cannot resolve symbol

thank you.
I wanted to add a simple TextSwitcher to a fragment, it's all good (I think) till this line:
TextView t = new TextView (TextSwitcherActivity.this);
I am missing out why it cannot resolve the symbol: TextSwitcherActivity.
Please, if you have any suggestions I would truly appreciate.
Here is the whole Java code, I believe is by the book, nothing new.
public class viewOne extends AppCompatActivity {
TextSwitcher switching;
Button pre_button, next_button;
String strTextSwitcher[] = {"Text 1", "Text 2", "Text 3, Text 4", "Text demo 5"};
int currentIndex = -1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_view_one);
next_button=(Button)findViewById(R.id.next_button);
pre_button=(Button)findViewById(R.id.pre_button);
switching=(TextSwitcher)findViewById(R.id.switching);
switching.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
TextView t = new TextView (TextSwitcherActivity.this);
t.setGravity(Gravity.TOP|Gravity.CENTER);
t.setTextSize(36);
return t;
}
});
switching.setCurrentText("click on the next button to switch text");
pre_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
if (currentIndex>0)
switching.setText(strTextSwitcher[currentIndex]);
}
});
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (currentIndex<strTextSwitcher.length-1)
currentIndex = currentIndex+1;
switching.setText(strTextSwitcher[currentIndex]);
}
});
}
}
Try
TextView t = new TextView (this);
//or
TextView t = new TextView (viewOne.this);

onclicklistener on the specific item of the recyclerview in android

I am going to ask very basic question, but i am stuck in it for a long time.
after card view there is an recycleview which has 2 images in each row.
now i want to create the click listener on the images rather than the recycleview.
the corresponding layout(layout_main.xml) of this activity(MainActivity.java) contain only recyclerview. the elements of each row is in another layout(layout_images.xml). i am getting the images from layout_images.xml and inflate them in the adapter class(Adapter.java).
now how to put action listener on the images only.
secondly, i want to get the image on which i clicked. how to get that.
like, when we click on a view we create some method as
public void onClick(View view){
// some code here
}
where view is the object on which we clicked. in my case how to get the image on which i clicked.
using type cast it might be throw an exception when user doesnot click on image.
Multiple onClick events inside a recyclerView:
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView iconImageView;
public TextView iconTextView;
public MyViewHolder(final View itemView) {
super(itemView);
iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);
// set click event
itemView.setOnClickListener(this);
iconTextView.setOnClickListener(this);
// set long click event
iconImageView.setOnLongClickListener(this);
}
// onClick Listener for view
#Override
public void onClick(View v) {
if (v.getId() == iconTextView.getId()) {
Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
}
//onLongClickListener for view
#Override
public boolean onLongClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Hello Dialog")
.setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
return true;
}
}
To get which item was clicked you match the view id i.e. v.getId() == yourViewItem.getId()
You have to set onClickListener to the ImageViews inside the onBindViewHolder method, refer the following LOCs for reference(code to be inside onBindViewHolder method)
holder.imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//put your code for first imageview here
}
});
holder.imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//put your code for second imageView here
}
});
In Recycle View Holder, Write your onclick listener code inside
#Override
public void onBindViewHolder(CardHolder holder, final int position) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO
}
}
}
implement the View.OnClickListener in your ViewHolder class and implement the onClick method. Then set the click listener for your ImageView to this click listener. Add the required functionality in the onClick method. If you want to implement the click functionality in other class simply create an interface and declare a click method in it. You can implement this method in the activity/fragment that contains this RecycleView. Then from your view holders onClick method you can invoke the interface method.
You can check with tag or it of element like this:
public void onClick(View view){
if(view.getId() == image1.getId())
{
}else if(view.getId() == image2.getId())
{}
}
First of all set onclickListener to each view you want to be clicked. Good place to do it in viewHolderConstructor. eg
public class GalleryManyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.im_img) RoundedCornersImageView imImg;
#BindView(R.id.tv_title) MyTextView tvTitle;
#BindView(R.id.tv_label) MyTextView tvLabel;
#BindView(R.id.tv_date) MyTextView tvDate;
#BindView(R.id.im_gallery_one) RoundedCornersImageView imGalleryOne;
#BindView(R.id.im_gallery_two) RoundedCornersImageView imGalleryTwo;
#BindView(R.id.im_gallery_three) RoundedCornersImageView imGalleryThree;
#BindView(R.id.im_gallery_four) RoundedCornersImageView imGalleryFour;
#BindView(R.id.tv_more) MyTextView tvMore;
#BindView(R.id.root) RelativeLayout root;
public GalleryManyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
view.setOnClickListener(onClickListener);
imGalleryOne.setOnClickListener(onClickListener);
imGalleryTwo.setOnClickListener(onClickListener);
imGalleryThree.setOnClickListener(onClickListener);
imGalleryFour.setOnClickListener(onClickListener);
view.setTag(this);
}
Generally you do not need to make anything specific with those view, like setting tags (Also some usefull libraries like Glied, which sets its own tags to imageviews will malfunction if you set you own tag. In on clickListener find adapter position of the view to be able to retrive the corresponding data
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override public void onClick(View v) {
View view = v;
View parent = (View) v.getParent();
while (!(parent instanceof RecyclerView)){
view=parent;
parent = (View) parent.getParent();
}
int position = recyclerView.getChildAdapterPosition(view);
}
as described here
Then but checking views id, evaluete what you want to do
switch (v.getId()) {
case R.id.im_gallery_one: {
p = 0;
}
break;
case R.id.im_gallery_two: {
p = 1;
}
break;
case R.id.im_gallery_three: {
p = 2;
}
break;
case R.id.im_gallery_four: {
p = 3;
}
break;
}

Categories

Resources