Android :- Separate class for handling views clicks etc; - java

I am new to development field. I am developing android application where in my activity_main layout I have many different items. On clicking one of the button the top layout is replaced with a new layout.
Now instead of defining the new layouts buttons, textview etc in my main class , I want to have a separate class which can initialize my buttons etc, and also in that class I can declare onClickListners.
In my main Activity I want:-
public void onCreate(){
button bb = (Button)findViewById(R.id.mybutton);
View CurrentContentView= getLayoutInflater().inflate(R.layout.activity_main, null, false);
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView);
}
});
}
In my MyNewViewInit() class :-
public class MyNewViewInit{
ImageButton backbutton;
ChipsMultiAutoCompleteTextview search;
ImageButton searchclear;
ImageButton modeTime;
ImageButton modeTag;
TextView modeTimeTxt;
TextView modeTagTxt;
ScrollView mainScroll;
ScrollView selectedScroll;
public MyNewViewInit(View v){
backbutton = (ImageButton)v.findViewById(R.id.backbutton);
search = (ChipsMultiAutoCompleteTextview)v.findViewById(R.id.search);
searchclear = (ImageButton)v.findViewById(R.id.searchclear);
modeTime = (ImageButton)v.findViewById(R.id.modeTime);
modeTag = (ImageButton)v.findViewById(R.id.modeTag);
modeTimeTxt = (TextView)v.findViewById(R.id.modeTimeTxt);
modeTagTxt = (TextView)v.findViewById(R.id.modeTagTxt);
mainScroll = (ScrollView)v.findViewById(R.id.HAT1);
selectedScroll = (ScrollView)v.findViewById(R.id.HAT2);
tag = new OtherHelper().arrayread();
mainHashTag.setVisibility(View.GONE);
selectedHashTag.setVisibility(View.GONE);
clickListners();
}
public void clickListners(){
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
searchclear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTimeTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
modeTagTxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
So when I try using this code the onclicklistners are not working.
What is the best way to do this.
Thanks

Write an Interface in your class,
class MyNewViewInit{
public interface ClickListenerInterface{
void onCLickSomething(Something something);
}
ClickListenerInterface mClickListener;
...
public MyNewViewInit(View v,ClickListenerInterface clickListener){
mClickListener = clickListener;
...
}
public void clickListners(){
...
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mClickListener!=null){
mClickListener.onCLickSomething(v);
}else{
//throw an error that activity should implement ClickListenerInterface
}
}
});
}
}
In your Activity,
class MyActivity extends Activity implements ClickListenerInterface{
public void onCreate(){
bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyNewViewInit(CurrentContentView,this);
//if using Android Studio, then use the context menu to implement the interface
}
});
}
void onCLickSomething(Something something){
//do something with something
}
}

You can try do a abstract class extends Activity, like :
public abstract class MyInitActivity extends Activity
{
EditText editText;
TextView textView;
#Override
public void setContentView(int layoutResID)
{
super.setContentView(layoutResID);
editText = (EditText)findViewById(R.id.editText);
textView = (TextView)findViewById(R.id.textView);
}
}
and in your main activity you can extend your abstract class, like :
public class MainActivity extends MyInitActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/*********** Listener ************/
public void onButtonClick(View v)
{
textView.setText(editText.getText().toString());
}
}
you can also implement onClick() in the abstract class
i don't know if its a good practice , i prefer do the methods with view arguments and set this methods in the layout.xml file .

I had use this in one of code
STEP 1
Declare button in layout(XML file)
STEP 2
Declare all ur button like this--
Button btn1 = (Button)findViewById(R.id.btn1);
Button btn2 = (Button)findViewById(R.id.btn2);
Button btn3 = (Button)findViewById(R.id.btn3);
............so on
STEP 3
implement View.OnClickListener
Now after step 2 do this
btn1.setOnClickListener(this);
.
.
.
same way for all
STEP 4:
Use switch case inside Onclick
public void OnClick(View v)
{
case:R.id.btn1{
//ur command similarly use multiple case stmt for many button
}
}

Related

setOnClickListener button doesn't work Android studio

I'm new in java and I have tried to make a food app in android studio. I have a bar in app and when I click on cart my app is crashing.
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView.Adapter adapter, adapter2;
private RecyclerView recyclerViewCategotyList, recyclerViewPopularList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewCategoty();
recyclerViewPopular();
bottomNavigation();
}
private void bottomNavigation() {
LinearLayout homeBtn=findViewById(R.id.homeBtn);
LinearLayout cartBtn=findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,CartActivity.class));
}
});
}
And I have this error: at com.example.food.Activity.MainActivity$2.onClick(MainActivity.java:48)
This is CartActivity
public class CartActivity extends AppCompatActivity {
private RecyclerView.Adapter adapter;
private RecyclerView recyclerViewList;
private ManagementCart managementCart;
private TextView totalFeeTxt, taxTxt, deliveryTxt, totalTxt, emptyTxt;
private double tax;
private ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
managementCart = new ManagementCart(this);
initView();
initList();
bottomNavigation();
calculateCard();
}
private void bottomNavigation() {
LinearLayout homeBtn = findViewById(R.id.homeBtn);
LinearLayout cartBtn = findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
}
I don't know what's wrong and why my setOnClickListener doesn't work.
Thank you.
I think your button R.id.homeBtn is not LinearLayout, can you show your xml file?
If your buttons are Button classes, try this
private void bottomNavigation() {
Button homeBtn = findViewById(R.id.homeBtn);
Button cartBtn = findViewById(R.id.cartBtn);
homeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
cartBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(CartActivity.this, MainActivity.class));
}
});
}

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

After an imageButton is clicked, how do I best disable other imageButtons, AND assign a variable with the selected imageButton’s value?

Context: My Style Activity corresponds to a layout with 4 imageButtons and a regular button. I want the user to only be able to select one imageButton at a time. Upon the click of the regular button, I want to send the data regarding which imageButton is selected to my ReviewActivity while simultaneously opening my ReflectionActivity.
I have 2 questions. First, how do I dry up my code surrounding OnClick's and disabled imageButtons? Second, how do I set a variable based on which imageButton was selected and send to another activity with an intent? I am fairly sure I've done this the long/hard way. All suggestions greatly appreciated!
public class StyleActivity extends AppCompatActivity {
Button btn_open_reflection;
ImageButton style1;
ImageButton style2;
ImageButton style3;
ImageButton style4;
public static final String style_selection = "com.example.application.hearttoart.style_selection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_style );
// set up image buttons for the onClick function
style1 = (ImageButton)findViewById(R.id.style1);
style2 = (ImageButton)findViewById(R.id.style2);
style3 = (ImageButton)findViewById(R.id.style3);
style4 = (ImageButton)findViewById(R.id.style4);
// TODO: DRY up when possible, lots of repeated code here
style1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style2.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style1";
}
});
style2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style2";
}
});
style3.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style2.setEnabled(false);
style4.setEnabled(false);
String style_selection = "#string/style3";
}
});
style4.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
style1.setEnabled(false);
style2.setEnabled(false);
style3.setEnabled(false);
String style_selection = "#string/style4";
}
});
btn_open_reflection =(Button) findViewById(R.id.btn_open_style);
btn_open_reflection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// Open Style Activity - Navigate to Activity from the Click
openReflection();
sendStyle();
}
});
}
public void sendStyle() {
Intent styleIntent = new Intent(StyleActivity.this, ReviewActivity.class );
styleIntent.putExtra("style", style_selection);
}
public void openReflection() {
Intent intent = new Intent( this, ReflectionActivity.class );
startActivity( intent );
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn_open_reflection;
ImageButton style1;
ImageButton style2;
ImageButton style3;
ImageButton style4;
String style_selection = "com.example.application.hearttoart.style_selection";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set up image buttons for the onClick function
style1 = (ImageButton)findViewById(R.id.style1);
style2 = (ImageButton)findViewById(R.id.style2);
style3 = (ImageButton)findViewById(R.id.style3);
style4 = (ImageButton)findViewById(R.id.style4);
btn_open_reflection =(Button) findViewById(R.id.btn_open_style);
btn_open_reflection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// Open Style Activity - Navigate to Activity from the Click
openReflection();
}
});
}
public void openReflection() {
Intent intent = new Intent( MainActivity.this, OtherActivity.class );
intent.putExtra("style", style_selection);
startActivity(intent);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.style1:
//disable other buttons
style2.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style1";
break;
case R.id.style2:
style1.setEnabled(false);
style3.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style2";
break;
case R.id.style3:
style1.setEnabled(false);
style2.setEnabled(false);
style4.setEnabled(false);
style_selection = "#string/style4";
break;
case R.id.style4:
style1.setEnabled(false);
style2.setEnabled(false);
style3.setEnabled(false);
style_selection = "#string/style4";
break;
}
}
}
This link might help.

How to change text in BaseAdapter

I am trying to change the text of button inside onClick() but it's not changing. I have tried the following -
viewHoder.btn_select_qq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHoder.btn_select.setText("xxxxx");
notifyDataSetChanged();
}
});
How to set it?
Try this -
viewHoder.btn_select_qq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
b.setText("xxxxx");
}
});

Caused by: java.lang.OutOfMemoryError

I am having a layout file and 5 buttons -- 1 for next and 2 for previous etc. Application runs fine, when I click first button, it loads the image correctly, then as I click another button, it gives the error -Caused by java lang Out Of Memory Error
public class MainActivity extends ActionBarActivity {
private ShareActionProvider mShareActionProvider;
ImageButton btn1;
ImageButton btn2;
ImageButton btn3;
ImageButton btn4;
ImageButton btn5;
ImageButton btn6;
ImageButton btn7;
ImageButton btn8;
ImageView image1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
addListenerOnButton2();
addListenerOnButton3();
addListenerOnButton4();
addListenerOnButton5();
addListenerOnButton6();
}
public void addListenerOnButton() {
btn1= (ImageButton) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.show);
}
}
);
}
public void addListenerOnButton2() {
btn2= (ImageButton) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.k2);
}
}
);
}
public void addListenerOnButton3() {
final Context context =this;
btn3= (ImageButton) findViewById(R.id.btn3);
btn3.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.k3);
}
}
);
}
public void addListenerOnButton4() {
final Context context =this;
btn4= (ImageButton) findViewById(R.id.btn4);
btn4.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.k4);
}
}
);
}
public void addListenerOnButton5() {
final Context context =this;
btn5= (ImageButton) findViewById(R.id.btn5);
btn5.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.k5);
}
}
);
}
public void addListenerOnButton6() {
final Context context =this;
btn6= (ImageButton) findViewById(R.id.btn6);
btn6.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
setContentView(R.layout.k6);
}
}
);
}
You are changing the whole layout instead of changing the image. When you do that, garbage collector is not called and you should be calling it on your own. Since it's not called, you are going to get that error pretty soon.
Do it like this instead
int[] imageArray = {R.drawable.image1, R.drawable.image2, ... };
and when you click a button, just do
btn1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
someImageView.setImageResource(imgageArray[0])
}
}
Also make sure you don't use too big images. The take up a lot of memory.

Categories

Resources