Can we to use the single Action Bar for all Activities? - java

I have Action bar and a lot of different Activity, its working, but I don't want to add code in every Activity. How to add one code in one Activity that will work in every Activity? I expect to write only one code in one Activity for all activities.
My main activity:
package ua.in.masterpc.technoguide;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ImageButton;
public class IconsMain extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icons_main);
ImageButton myImageButton = findViewById(R.id.iconPC);
myImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentLoadNewActivity = new Intent(IconsMain.this, PCProblems.class);
startActivity(intentLoadNewActivity);
}
});
}
#Override//start menu code
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.bar_menu, menu);
return true;
}//end menu code
}
Thank you for answers!

You can create class named BaseActivity which will extend AppCompatActivity and put there the code and functionality you want to use in every other Activity. Then in every of your activities, you will extend BaseActivity instead of AppCompatActivity. By doing that you can avoid duplicating your code. Remember that you will have to put ActionBar in every activity .xml layout file.

create a baseActivity
add function inside it to initialize the toolbar and customize it as you like
open class BaseActivity : AppCompatActivity() {
protected fun initializeToolbar() {
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
}
}
create toolbar_main.xml
extends the baseActivity in any activty after including the toolbar_main.xml as <include layout="#layout/toolbar_main" />
class MainActivity : BaseActivity(){
}
and call the function you created in baseActivity.

Create a layout say, toolbar_layout, and add the the code for your layout, then include the layout in all your activities:

Related

Simple swipe screen using VIewPager2 (Java)

I am trying to create layout which will show three screens which could be changed by swipe or by button. Between those buttons should be dots indicator of selected page.
I spent many time searching of samples how to do it, but usually I stucked on some issue. I don't need option of dynamical adding of fragments. The best and working solution was thisone, but I wasn't able to create three different fragments and it was missing the dots indicator.
Could someone help me with this issue? Thank you very much.
you can just have a new class that extends to FragmentStateAdapter and set the class as the adapter of your viewpager like so:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
ViewPager2 viewPager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager2 = findViewById(R.id.viewpager2);
viewPager2.setAdapter(new ViewPagerFragmentAdapter(this));
}
static class ViewPagerFragmentAdapter extends FragmentStateAdapter {
public ViewPagerFragmentAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new Vertical1();
case 1:
return new Vertical2();
case 2:
return new Vertical3();
}
return new Vertical2();
}
#Override
public int getItemCount() {
return 3;
}
}
}
You can create a adapter by extending from RecyclerView.Adapter() and use simple layouts(not fragments) for every page and set that adapter to viewpager2.adapter = adapter

Different behavior of android.app.Fragment and android.support.v4.app.Fragment while using backstack

I've created Activity and added a fragment to it using FragmentManeger. When i use android.app.Fragment and press the back button my application closes. When i use android.support.v4.app.Fragment and press the back button, the fragment is removed from the activity, but application is still working. I can't really understand why is that happening.
Here is the code i used:
Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(R.id.content_fragment, new Fragment1())
.addToBackStack("first")
.commit();
}
}
Fragment:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 extends Fragment {
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}
When i simply replace import in Activity and Fragment to same classes, but in the support library, the result is different...
EDIT:
I also replaced getFragemetManeger() to getSupportFragmentMeneger() and it still works different
if you're only looking to change the back behavior, you can try overriding
onBackPressed with something like:
if(backstackCount() > 0)
{
super.onBackPressed
}
The issue occured because i used android.support.v7.app.AppCompatActivity and android.app.Fragment. I should've used android.app.Fragment with android.app.Activity or AppCompatActivity with support fragment.

How to put Interfaces in a library for android App

to the point, i am working in a library for android app's, all programing part is almost finish, i am testing a idea.
the idea is put some interfaces in the librery that i am working, and this GUI can be loaded in the main app.
i try to do it but i get to error the first was i did not declare the activity in the AndroidManifest in the main app, the second one is the one a i cant solve, the autogenerated Class R don't capture the GUI that it is in the librery.
it is anyway i can do this or it is imposible.
code to see what i am trying todo
in my librery (movilsecure)
EmisionActivity.java (have the activity_emision.xml in the res of my librery)
in the Main Android App (
import ve.com.idyseg.movilsecure.EmisionActivity;
import ve.com.idyseg.movilsecure.MSMasterControllerTEST;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void captureEvent (View v){
Intent intento = new Intent(this,EmisionActivity.class);
startIntent(intento);
}
}
In Eclipses, right click the project, the click Build Path then click Add Library. Please comment if you're still stuck.
In the library's manifest, in the <activity> node, did you set android:exported="true"?
Example:
<activity
android:name="com.example.app.EmisionActivity"
android:exported="true">
</activity>

Onclick imagebutton-action (menu)

I'm making an app and when it launches it starts Mainactivity.java
Mainactivity.java opens a layout with 9 Imagebuttons.
How can I implement in my code in Mainactivity.java that once one is clicked it opens another activity (like telefoonnummers.java)?
Sorry for my bad English but I'm dutch and a non-native speaker.
I have this code in Mainactivity.java:
package com.example.rome;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Very clean as you see, but how can I add the implementation, would you guys please help???
My Imagebuttons are all just called imagebutton1, imagebuttton2 etc. btw.
After
setContentView(R.layout.activity_main);
add for each ImageButton:
findViewById(R.id.imagebutton1).setOnClickListener(this);
Make class implement OnClickListener
class MainActivity extends Activity implements View.OnClickListener {
and add this method:
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.R.id.imagebutton1:
startActivity(new Intent(telefoonnummers.class));
break;
case R.id.R.id.imagebutton2:
startActivity(new Intent(telefoonnummers.class));
break;
//-- more cases --
}
}

What is the best way to instantiate widgets which are pre-defined in XML layouts in a custom View class?

I am rather new to Android programming in general and am having particular difficulty with the xml/java UI shuffle... I have a layout which I would like to use as the view displayed when a custom, view class is instantiated in the activity class. This much works fine by simply calling
setContentView(R.layout.mylayout) ;
in the activity or from the custom view class through a handle to the activity. The trouble comes when I wish to interact with the widgets on the layout-- I've tried getting a handle on the buttons with
myButton = (Button) findViewById(R.id.mybuttonid);
and separately with
Button myButton = new Button(contextHandle);
myButton = (Button) findViewById(R.layout.mybuttonid);
but in both cases whenever I try to call any methods from the assumed myButton object I get a NullPointerException in the logcat report; evidently myButton is not properly instantiated in either case given above. What is the proper way to instantiate components of a view in a case like this that combines xml and java so that they can call methods dynamically?
thanks,
CCJ
EDIT: Thanks all for the replies, but I think up to 8/1/2011 the advice has been mostly targeted at an implementation wherein the widgets are to be instantiated in the activity class; I wish to instantiate widgets from an xml layout in a custom view class-- a class completely separate from the activity class which extends View and implements its own OnClickListener interface. Below is my code:
MyActivity Class:
package com.ccg.myactivity;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
public class MyActivity extends Activity implements OnClickListener {
private boolean touched = false;
private RadioButton myRB;
private Button runB;
private CustomView myView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
myRB = (RadioButton) findViewById(R.id.testrb);
runB = (Button) findViewById(R.id.goButton);
//set onClick listeners for activity class
runB.setOnClickListener(this);
}
public void onResume(){
super.onResume();
}
public void onClick(View v) {
// do something when the button is clicked
if (myRB.isChecked()){
setContentView(R.layout.mylayout);
myView = new CustomView(this,this); //passing in activity and context
//handles to custom View class
//myView.getAnotherB().setOnClickListener(this); //commented out as we
//don't want to register the custom view's button with the Activty class's
//OnClickListener; instead it should be registered with the custom View class's own
//OnClickListener implementation.
}
else{
Log.d("me","alt click");
}
}
}
CustomView Class:
package com.ccg.myactivity;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View.OnClickListener;
public class CustomView extends View implements OnClickListener{
private Button anotherB;
private Context contextHandle;
private Activity actHandle;
public CustomView(Context context, Activity act) {
super(context);
contextHandle = context;
actHandle = act;
//anotherB = new Button(contextHandle); //this shouldn't be necessary for
//instantiation from XML widget
initCustomView();
}
public void initCustomView(){
anotherB = (Button) findViewById(R.id.nextbutton);
anotherB.setOnClickListener(this);
}
public Button getAnotherB(){
return anotherB;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("me", "Got the custom click!");
}
}
mainlayout.xml from which the default view is made:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/widget474"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<RadioGroup android:id="#+id/widget30" android:orientation="horizontal"
android:layout_x="2dip" android:layout_y="57dip" android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton android:layout_height="wrap_content" android:id="#+id/testrb"
android:textSize="15sp" android:text="Run" android:layout_width="wrap_content"
android:textColor="#ffff99ff"></RadioButton>
</RadioGroup>
<Button android:layout_width="wrap_content" android:text="#string/RUN"
android:id="#+id/goButton" android:layout_height="wrap_content"
android:layout_x="222dip" android:layout_y="110dip"></Button>
</LinearLayout>
mylayout.xml from which the custom view's layout is created:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Button android:id="#+id/nextbutton" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="work!!!"
>
</Button>
</LinearLayout>
okay, if anybody can explain why any method calls from the button object anotherB (anotherB.setOnClickListener(this) above, but also the simpler anotherB.bringToFront()) cause a force close and a nullpointerexception in logcat with the above implementation I would be most appreciative. thanks!
CCJ
I would declare your button outside of onCreate without the contextHandle parameter... The context will be imbedded in your button upon instantiation (as I understand it).
try:
class YOUR_CLASS {
Button myButton;
onCreate() {
myButton = (Button) findViewById(R.id.WHATEVER_YOU_CALLED_IT_IN_XML);
then you can set an onClickListener or other abilities (you can google that, its easy)
myButton.setOnClickListener(myOnClickListener);
myButton.setText("click me!");
}
}
This sometimes happens to me when the import isn't correct. Sometimes Eclipse will fill in the import as:
import android.R;
of course, this will never find your ID. You should either not have an import, or have something like
import com.myco.mytestapp.R;
If you do that, then the first way of doing it is correct:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
Button b = (Button) findViewById(R.id.mybutton);
}
Okay, thanks to some advice from the android developers google group I think I've found the answer to at least the most pressing concern (the NPE and force close):
I needed to override onFinishInflate in my custom View class; it is at that point that my XML layout child views (like anotherB) are truly instantiated. The class now looks like this
package com.ccg.myactivity;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.view.View.OnClickListener;
public class CustomView extends View implements OnClickListener{
private Button anotherB;
private Context contextHandle;
private Activity actHandle;
public CustomView(Context context, Activity act) {
super(context);
contextHandle = context;
actHandle = act;
//anotherB = new Button(contextHandle); //this shouldn't be necessary for
//instantiation from XML widget
initCustomView();
}
public void initCustomView(){
anotherB = (Button) findViewById(R.id.nextbutton);
anotherB.setOnClickListener(this);
}
public Button getAnotherB(){
return anotherB;
}
#Override
public void onFinishInflate(){
anotherB.setOnClickListener(this); //it seems any addressing of child
//views of the layout [the widgets] need to be made after the
//framework calls this method.
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("me", "Got the custom click!");
}
}
Now it pulls up the layout properly and does not throw an NPE. Of course, the onClickListener callback still isn't working right (the message 'Got the custom click!' never appears in logcat), but that's another issue...
thanks all
CCJ
Okay, finally had some time to revisit this issue and I believe I've found the answer:
First, before the xml layout or its components can be addressed they need to be inflated. I knew this, but I wasn't sure when exactly they were inflated. It turns out that setContextView (and probably addContextView) trigger xml inflations. In order to have completely modular activity/view classes, I needed to do something like the following:
Activity Class--
package com.ai.ultimap;
import com.ai.ultimap.views.HomeView;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
public class UltiMapActivity extends Activity {
private View hv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hv = new HomeView(this);
}
}
Custom View Class-
package com.ai.ultimap.views;
import com.ai.ultimap.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
public class HomeView extends View implements OnClickListener{
private RadioButton twodRB;
private RadioButton threedRB;
private TextView locTV;
private EditText editlocET;
public HomeView(Activity hAct) {
super(hAct);
//THE FOLLOWING LINE INFLATES-- IT (or another function which calls xml inflation)
//MUST COME BEFORE ANY JAVA ADDRESSING OF WIDGETS IN
//THE XML LAYOUT
//Also note that even though you could invoke findViewById from a class extending
//View, in this case you must use hAct.findViewById. I believe this is due to the
//fact that the activity referenced by hAct is the object responsible for inflating
//the xml and thus the widgets need to be instantiated from it.
hAct.setContentView(R.layout.ultimap);
twodRB = (RadioButton) hAct.findViewById(R.id.twodRBV);
threedRB = (RadioButton) hAct.findViewById(R.id.threedRBV);
locTV = (TextView) hAct.findViewById(R.id.locationTV);
editlocET = (EditText) hAct.findViewById(R.id.locationETV);
//After instantiation however they can be freely accessed from java in
//non-activity classes, which is the point; see the next line...
twodRB.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locTV.setText("yo");
}
}
This code works properly to load up the pre-defined xml view ultimap.xml and then address the widgets dynamically from Java (completely outside the activity class), changing the text of the location text view from 'Location' to 'yo' when the twodRB radiobutton is clicked!
Hope this helps some googlers :)
-CCJ

Categories