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
Related
I have rather simple task to complete, but I can't get my head around it, I have my main class here, I choosing between screens using buttons, My task is to create a About page just explaing the rules of the game (my application).
public class Hashi_Main extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up click listeners for all the buttons
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
// click handling
public void onClick(View view) {
switch (view.getId()) {
case R.id.exit_button:
finish();
break;
case R.id.new_button:
NewGame();
break;
case R.id.about_button:
NewGame();
break;
}
}
And here i create a my NewGame activity this all works.
public void NewGame() {
// We first ask for the difficulty level.
new AlertDialog.Builder(this)
.setTitle(R.string.new_game_title)
// we provide a char array with the on click listener.
.setItems(R.array.difficulty,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int hardness) {
Intent intent = new Intent(Hashi_Main.this, HashiGame.class);
intent.putExtra(HashiGame.KEY_DIFFICULTY, hardness);
startActivity(intent);
}
})
.show();
}
What I want to do is the same thing but to use it for about page, I want to use TextView for the rules, this activity will have nothing else except text and a back to main menu button. I tried something like this.
public void About() {
LinearLayout lheader = new LinearLayout(this);
lheader.setOrientation(LinearLayout.HORIZONTAL);
TextView about_rules = new TextView(this);
about_rules.setId(about_id);
lheader.addView(about_rules);
}
But I am stuck for a while now, how can i trigger this activity?
Create an about activity and use an intent to launch your newly created activity. like so:
Intent intent = new Intent(Hashi_Main.this, AboutActivity.class);
startActivity(intent);
I cannot see any Activity in the About() method. It is just a local LinearLayout with a TextView.
You need to learn more about Android development before making any app.
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;
}
}
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;
}
}
});
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).
https://github.com/jfeinstein10/SlidingMenu
I am using this library, i would like to hide the sliding-menu when i open an new activity, so that when i press back i don't want the sliding menu to appear.
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent("android.intent.action.Home");
getActivity().startActivity(intent);
break;
}
}
The above code is in my SherlockListFragment class, i would like to hide the sliding-menu, once i start a new activity.
If you've extended SlidingActivity, then all you need is:-
toggle();
That should do it :-)
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
switch (position) {
case 0:
Intent intent = new Intent("android.intent.action.Home");
getActivity().startActivity(intent);
// Toggle the sliding menu
((YourHostActivity) getActivity()).getSlidingMenu().toggle();
break;
}
}
In your activity that hosts the sliding menu:
public onCreate(...) {
// save the slidingmenu instance to a propery
mSlidingMenu = new SlidingMenu(this);
}
// create a getter
public SlidingMenu getSlidingMenu() {
return mSlidingMenu;
}