Creating a reusable class - java

I have an application running in Android, i wanna create a Menu and repeat in some activities, that menu calls Intent for open others activities.
How can i do this?
Think maybe i can create a class, but i getting errors. Where can i create a class for that? Inside onCreate method or not?
And how can i reuse the menu in another activity?
Thanks!!
Here is my menu code:
menu_button = (Button) findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(MainActivity.this, openCamera.class);
MainActivity.this.startActivity(vista);
}
return true;
/*
Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
*/
}
});
popupMenu.show();
}
});

If the menu is always the same and you want to reuse it in more than one activity, you just define it like this:
public class TestMenu {
private final PopupMenu popupMenu;
public TestMenu(final Activity activity, View anchor) {
popupMenu = new PopupMenu(activity, anchor);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(activity, openCamera.class);
activity.startActivity(vista);
}
return true;
}
});
}
public void show() {
popupMenu.show();
}
}
And then use it in your activity like this:
public class TestActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button menu_button = (Button) findViewById(R.id.menu_button);
TestMenu myMenu = new TestMenu(this, menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMenu.show();
}
});
}
}

Related

Whe button continueButton isnt working? It should start the new Activity if I have a text in EditText or make a Toast

I work with a program which should make parameters for character. A person writes a name then generate force and health by clicking the button. After all, he click the continueButton which should start the MainActivity if name exists or make a Toast text. But it's not working. The problem should be in the end of onClick method.
There is a code
public class CreateActivity extends AppCompatActivity
implements View.OnClickListener {
final Random random = new Random();
String toastText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
}
#Override
public void onClick(View v) {
Button continueButton = findViewById(R.id.continueButton);
Button getData = findViewById(R.id.getData);
final EditText newName = findViewById(R.id.newName);
TextView newHealth = findViewById(R.id.newHealth);
TextView newForce = findViewById(R.id.newForce);
continueButton.setOnClickListener(this);
getData.setOnClickListener(this);
newName.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()== KeyEvent.ACTION_DOWN &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
Character.name = newName.getText().toString();
return true;
}
return false;
}
});
switch (v.getId()){
case R.id.getData: {
Character.health = random.nextInt(100);
newHealth.setText(String.valueOf(Character.health));
Character.force = random.nextInt(100);
newForce.setText(String.valueOf(Character.force));
}
// THERE IS A PROBLEM
if (newName.getText().toString().equals("")) {
switch (v.getId()) {
case R.id.continueButton:
startActivity(new Intent(this, MainActivity.class));
finish();
return;
}
} else{
switch (v.getId()) {
case R.id.continueButton:
Toast toast = Toast.makeText(this, toastText, Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
}
Initialize your Button inside onCreate method. Like this:
public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
private Button yourButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourButton= findViewById(R.id.your_button_id);
yourButton.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.your_button_id:
// Do something
}
}
}

Why are my buttons not working in Android Studio?

I am doing A Level computing and I'm trying to make an app for my Comp 4 project. All the other classes i have done with buttons seem to be working fine but the buttons on my main menu are not working.
public class MainActivity extends AppCompatActivity {
Button bLogin;
Button bProducts;
EditText etName, etAge, etUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
break;
case R.id.bProducts:
break;
}
return super.onOptionsItemSelected(item);
}
public void ProductsOnClick(View b) {
startActivity(new Intent(".Products"));
switch (b.getId()) {
case R.id.bProducts:
}
}
public void LoginOnClick(View a) {
startActivity(new Intent(".Login"));
switch (a.getId()){
case R.id.bLogin:
}
}
}
This Activity runs but the buttons on the Options Menu don't work.
I am using Android Studio to program this.
Because there is nothing to execute when the menu item is selected, change your code like that:
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
startActivity(new Intent(".Login"));
break;
case R.id.bProducts:
startActivity(new Intent(".Products"));
break;
}
return super.onOptionsItemSelected(item);
}
PS:
Make sure that you're using the right Intent constructor, because with Intent(String) you need an action as parameter not an activity name or something else.
You can use OnClickListener instead. Put this in your onCreate:
bProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Products"));
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Login"));
}
});

Eclipse, new activity on button click

I'm a beginner but I would like to modify an older project.
On the Preferences Activity, there are already few buttons, but I would like to add a new button, which, when clicked, opens a new Activity and shows an image only.
For this I declared this new activity in the Manifest:
<activity
android:name=".VisualHelpActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" >
</activity>
I declared the button on the associated xml layout:
<Button
android:id="#+id/button_visualhelp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="visual_help"
android:text="Visual Help" />
I created the new VisualHelp layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/visualhelp_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/guide" />
Declared its new VisualHelpActivity java file:
public class VisualHelpActivity extends TranslatableActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visual_help, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void refreshLanguage() {
}
}
… and now I’m supposed to connect it all together in the "main" PreferencesActivity, which looks as follows:
public class PreferencesActivity extends TranslatableActivity {
public static String url = "https://www.paypal.com/cgi-bin....";
ImageView donate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}
private int getPosition(Object[] objs, Object item) {
for (int i = 0; i < objs.length; i++) {
if (objs[i] == item)
return i;
}
return -1;
}
public void update(View v) {
Maintenance.downloadDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void copy(View v) {
Maintenance.copyDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void save(View v) {
LanguageUtil.saveLanguage(this,
(Lang) ((Spinner) findViewById(R.id.combo_language))
.getSelectedItem());
LanguageUtil.loadLanguage(this);
setResult(RESULT_OK);
finish();
}
public void donate(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
public void cancel(View v) {
finish();
}
#Override
protected void refreshLanguage() {
((Button) findViewById(R.id.button_update)).setText(LanguageUtil
.getDeviceLabel(LanguageUtil.dev_update));
((TextView) findViewById(R.id.language_label))
.setText(LanguageUtil.getDeviceLabel(LanguageUtil.dev_language));
}
}
According to androidbegin.com, I should add this code into the PreferencesActivity java file (code above):
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
}
The only problem is that if I try to add this new public void, multiple marker errors pop up, and if I try to include all below somewhere else, my app fails to work. So, can anyone help me out where and how to include this code part to make it work?
add the code inside oncreate method like this in your PreferencesActivity class:-
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}

How to set Context menu to onBackPressedButton?

I'm trying to set Context menu to onBackPressedButton like "Are you sure to quit?"
Here I override onBackPressed:
I don't know how to call menu. What should I register here?
#Override
public void onBackPressed() {
registerForContextMenu();
return;
}
or what view should I attach?
#Override
public void onBackPressed() {
this.openContextMenu();
return;
}
Should I create viewList to it?
I've overridden onCreateContextMenu:
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0,YES,0,"Yes");
menu.add(0,NO,0,"No");
}
I've also overridden and onContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case YES:
finish();
break;
case NO:
break;
}
return super.onContextItemSelected(item);
}
How must I do it?
Just call onBackPressed() method in your class. Find a sample code below.
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
LoginActivity.super.onBackPressed();
finish();
}
}).create().show();
}

onBackPressed() doesn't work for me

I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}
the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files

Categories