I am new to the fragment.
in Activity, I have two onClick methods which are:
click that override the method
normal onclick
how can I change the onclick that override the method to fragment?
private void searchMobileNumber() {
mRecyclerView.addOnItemTouchListener(new SelectExistingOrNewNoFragment.RecyclerTouchListener(PostpaidRegistrationActivity.this, mRecyclerView, new SelectExistingOrNewNoFragment.ClickListener() {
#Override
public void onClick(View view, int position) {
selectedPostion = position;
mob_number_detail_lyt.setVisibility(View.GONE);
mobile_no_head_lyt.setVisibility(View.VISIBLE);
mobile_number_success.setImageDrawable(getResources().getDrawable(R.drawable.validation_correct));
if (simCardFirstTime) {
simCardFirstTime = false;
final Intent intent = new Intent(PostpaidRegistrationActivity.this, MyScanActivity.class);
intent.putExtra("ocrType", "Barcode");
intent.putExtra("message", "Please scan your SIM card");
startActivityForResult(intent, MposConstants.SIMCARD_FIRST_TIME);
}
}
}
If I get this clear, you have two buttons. One of which is to start a fragment or do something with it.. You just need a switch case. Also, use the R class for the cases.
Use view.getId()
Code:
#Override
public void onClick(View view, int position) {
switch(view.getId()){
case R.id.fragment_button:
// do something with fragment
break;
default: break;
}
}
Related
At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.
This is the code I'm working on:
public class EscolhaAtendimento extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotLayout;
String TAG = "TasksSample";
private TextView[] mDots;
private SliderAdapter sliderAdapter;
Dialog myDialog;
#Override
public void onCreate (Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.escolha_atendimento);
mSlideViewPager = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
sliderAdapter = new SliderAdapter(this);
mSlideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSlideViewPager.addOnPageChangeListener(viewListener);
myDialog = new Dialog(this);
}
public void addDotsIndicator(int position){
mDots = new TextView[8];
mDotLayout.removeAllViews();
for (int i= 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if (mDots.length > 0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected (int i) {
switch (i) {
case 0: {
myDialog.show();
}
addDotsIndicator(i);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
public void ShowPopup(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
}
This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).
Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).
Edit
I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:
Added
public ImageButton popupchoice;
And also this to onCreate method:
popupchoice = this.findViewById(R.id.imgslide1);
Inside the switch I called it like this to get the button ID:
popupchoice.setOnClickListener(image1);
And set the View.OnClickListener like this:
View.OnClickListener image1 = new View.OnClickListener() {
public void onClick(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
};
But that returns me:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81) Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).
This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.
I think you can use
EscolhaAtendimento.this.ShowPopup from inside your switch.
How to change text button when click in adapter
I try it's not work
public void setQuestData(final ViewHoder viewHoder, final int position) {
viewHoder.btn_select_qq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!profileFeedListModelTwos.get(position).getStatus_select().equalsIgnoreCase("SELECTED")){
viewHoder.btn_select_qq.setText("Accepted");
notifyDataSetChanged();
}
notifyDataSetChanged();
}
});
How to fix it ? and where is my problem?
Do not handle the click event inside the adapter class , instead handle it in the fragment using BaseRecyclerViewAdapter.OnRecyclerViewInteractionListener() or adapter listener of the adapter that you are using.
Set position as a tag inside your adapter then use it get the item in your fragment.
Make your adapter extend BaseRecyclerViewAdapter or adapter that you are using
Basic Idea
adapter = new Adapter(enter code here for setting click listener)
Inside YourAdapter just set the clickListener to your view
viewHoder.btn_select_qq.setOnClickListener(this)
Inside your fragment handle the action on click
YourAdapter adapter = new YourAdapter(getActivity(),new BaseRecyclerViewAdapter.OnRecyclerViewInteractionListener() {
#Override
public void onClick(View view) {
int position = (int) view.getTag();
ItemObject item =adapter .getItem(position);
switch (view.getId()) {
case R.id.view1:
//TODO write logic here
break;
case R.id.view2:
//TODO write logic here
break;
case R.id.view3:
//TODO write logic here
break;
}
}
});
I'm working on simple android project that require spinner widget in android studio. what i want to do is, when a user select choices from the spinner it will open another activity. while i'm in the middle of the coding. I decided to use switch case condition with Intent. The problem is whenever i run the application it will automatically go to the specific activity location that i declare. Even though I didn't select any choice on spinner.
Note: log cat doesn't show any error
Your help is very much appreciated to beginner like me.
public class CustomOnItemSelectedListener extends Activity implements
OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// **************************** below here is where I start the new activity
switch (pos) {
case 0 :
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1 :
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2 :
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
// **************************** above here is where I start the new activity
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Try this
Declare an int in your class, e.g. before onCreate(), then in your onCreate() you assign it to 0. Use this variable to check if its bigger than 0 when selecting something with your spinner, example below.
public class ExampleActivity extends AppCompatActivity {
private int spinnerCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinnerCheck = 0;
mMySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int itemId = (int) id;
// For some reason this method is called during initialization, so increment counter once to prevent it from auto selecting first item when loading view
spinnerCheck += 1;
if (spinnerCheck > 1) {
switch (pos) {
case 0:
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1:
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2:
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
For some reason it selects the first item once created, not sure why, but this should work.
When the application is created by default the first option is selected in your spinner and your listener is called. To avoid this you can use the solution of #Simon
or you can use a button to confirm your selection and change your activity when this button is pressed and not when an item is selected in your spinner.
UPDATE
You can also populate the first entry of your spinner with a useless text which can be a title like "Select activity" and start your switch in the listener to 1 and not 0
I'm working on a soundboard and I want to implement a long click to share the sound.
I am working with a switch Case for each button
public void MainMMP(View view){
switch (view.getId()) {
case R.id.button1:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx1);
MainMMP.start();
break;
case R.id.button2:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx2);
MainMMP.start();
break;
case R.id.button3:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx3);
MainMMP.start();
break;
And now I want to implement the long click. I tried a lot of different code here but it is not working for me.
I do not know where to put the onLongClick statement and how.
Can somebody show me a working method and in case of long click it should just send me a Toast that I know the method works?
You could add the OnLongClickListener where you want, in the onCreate method for example.
Try to use the following code:
Button button = (Button)findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Your code
return false; // True if you want to execute simple click code too
}
});
You can use this
private View.OnLongClickListener listener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
switch (view.getId())
case R.id.button1:
// Do something...
break;
case R.id.button2:
// Do something else...
break;
// If you still want to get normal click callbacks return true,
// if you do not then return false.
return true;
}
}
Somewhere in your code
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
Or better this
One common recommended way to get onClick/onLongClick/whatever callbacks is to make the Activity implement the callback interfaces.
class YourActivity extend Activity implements View.OnLongClickListener {
#Override
public boolean onCreate(/* ... */) {
// ...
button1.setOnLongClickListener(this);
button2.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
// Same code as the one above
}
}
My idea is that I have buttons on my app that leads to a single activity. I want it to have the same text template but different contents appearing when different buttons are clicked. I already have the XML file done, I got stuck on the code. I was thinking of using switch case but can it be possibly done with switch case? Or am I being too ambitious?
EDIT: Here's the code I have so far:
public class SelectKeys extends Activity {
private static final int[] buttonIDs = {R.id.cKey, R.id.cSharpKey, R.id.dKey, R.id.dSharpKey, R.id.eKey, R.id.fKey, R.id.fSharpKey, R.id.gKey, R.id.gSharpKey, R.id.aKey, R.id.aSharpKey, R.id.bKey};
private Button[] bt = new Button[buttonIDs.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_keys);
for (int i = 0; i < buttonIDs.length; i++) {
final int b = i;
bt[b] = (Button) findViewById(buttonIDs[i]); // Fetch the view id from array
bt[b].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opens up new screen
Intent intent = new Intent(getApplicationContext(), ChordKeys.class);
startActivity(intent);
}
});
}
}
public final void keyButton(final View v)
{
switch(v.getId())
{
case R.id.cKey:
{
setContentView(R.layout.activity_key_c);
break;
}
case R.id.cSharpKey:
{
setContentView(R.layout.activity_csharp_dflat);
break;
}
// adding more cases later once I get this to work
}
}
}
Of course it can be done with a switch case, you just need to create a class that implements onClickListener, and link all your buttons with this listener, like this:
final Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new MyButtonListener());
class MyButtonListener implements View.OnClickListener{
#Override
public void onClick(View v) {
int id=v.getId();
switch (id){
case R.id.button1:
button.setText("Text1");
break;
case **:
break;
default:
break;
}
To have a centralized Click handler which can be addressed in your xml layout:
Add this method to your Java code
public final void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btn1:
{
// Do something, when you click btn1
break;
}
case R.id.btn2:
{
// Do something else, when you click btn2
break;
}
// ... more cases ...
}
}
In your xml layout:
...
<Button
android:id="#+id/btn1"
...
android:onClick="clickHandler"
/>
<Button
android:id="#+id/btn2"
...
android:onClick="clickHandler"
/>
...
Note (1): This is valid not only for Buttons, but also for ImageButtons, ImageViews, TextViews, ...
Note (2): You can use it with mixed Views at the same time (i.e.: a Button, 2 TextViews and an ImageView can all address the same clikHandler() method).