I wanted to use a custom color and font and size for my app's name in the action bar, so I went in and stylized it in MainActivity.java like so
//stylize the action bar
TextView tv = new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setText(R.string.Title);
tv.setTextSize(45);
tv.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "KGALittleSwag.ttf");
tv.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(tv);
updateOptionsMenu();
This did the trick, and then when I added another activity I copied this code into it, and it looked great. At this point my app is almost ready to release, but I'm doing some refactoring and I now have 6 or so activities, and it feels more than a little redundant to put this code in each of them. Is there a better practice for applying these changes to the action bar universally?
This is what inheritance is for.
Create an abstract BaseActivity Class, in which you'll fo all these processing. All your activities where you want to apply these styles will inherit for BaseActivity.
public abstract class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
//stylize the action bar
TextView tv = new TextView(getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams (ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setText(R.string.Title);
tv.setTextSize(45);
tv.setTextColor(Color.parseColor("#FFFFFF"));
Typeface tf = Typeface.createFromAsset(getAssets(), "KGALittleSwag.ttf");
tv.setTypeface(tf);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(tv);
updateOptionsMenu();
}
}
Then your children activities:
public abstract class ChildActivity extends BaseActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState); // Here it calls the parent onCreate method and therefore executes the styling code
}
}
What you can do is just make a XML layout file for your custom action bar, and than use that in all activities.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/actionBarTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:gravity="center"
android:maxLines="1"
android:text="your text"
android:textAlignment="center"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold" />
</RelativeLayout>
make sure that your TextView is centered, and that layout_width and layout_hight for your TextView is set to wrap_content
Than put this into every activity that you want to use custom action bar
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_action_bar);
Related
I am new to java for android.
Then I attempt to put in textview anything, all views do not be shown.
Main.XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/textNew"
android:text="Hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="75px"/>
<Button
android:id="#+id/buttonNew"
android:text="Click me!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
int randomInt;
TextView textNew = findViewById(R.id.textNew);
SharedPreferences sp = getSharedPreferences("settings", Activity.MODE_PRIVATE);
Button clickButton = findViewById(R.id.buttonNew);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textNew.setText("5");
randomInt = Integer.parseInt(sp.getString("setting", "0"));
}
}
I tried to delete textNew.setText("text"). It is helped. But how I can set text!? Me need it!
You can't access the button and the Textview before setting the view content
SetContentView(View) sets the activity content to an explicit view.
In your case, you're setting the view to R.layout.main where the Button and the TextView are defined
To fix this move the onCreate and the setContentView before the rest of the code in the onCreate method
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
I can't figure out how to access my RelativeLayout programmatically so that I could call a method such as relativeLayout.getChildCount(); inside a Handler.
Edit - alright, if I wanted to get the total number of Views in my RelativeLayout, what function would I call?
In folder res/layout, I assume your layout named layout.xml
make sure your RelativeLayout have android:id segment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/myRelativeLayout" > //the id name can be acsessed in activity
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
access that RelativeLayout id in activity
public class mainActivity extends Activity {
//make variable globally
RelativeLayout myRelativeLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the layout file
setContentView(R.layout.layout);
//access the RelativeLayout and initialiszed the object
myRelativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
myRelativeLayout.getChildCount();
}
}
I am new with coding Java and xml for android applications and I wanted to know how I start/open a new activity when clicking on something. In this case I am using a relative layout to keep a image and text together as one object. What I want to do is when you click on it it will start/open the new activity. How do I do this? Could someone tell me step by step since I am quite new to this.
First of all, if you want your layout to act (RelativeLayout) like a button (do not handle onClick on layout child components) firstly set in your xml layout file RelativeLayout attribute
android:clickable="true"
Or you can do this directly in your code (in onCreate method)
relativeLayout.setClickable(true);
Than you need to set onClickListener for your layout.
You can do this simply by creating anonymous class
relativeLayout.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent startActivityIntent = new Intent(getApplicationContext(),YourDesiredActivity.class);
startActivity(startActivityIntent);
}
}
UPDATE
Layout is defined in xml file, of course in Android you can do this in code ,but it is better to use xml file.
In your IDEA you have folder res->layout here you should place your layout files. For example layout with name `
relative_root_layout.xml
<xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_layout"
android:layout_height="wrap_content" android:layout_width="wrap_content">
<ImageView
android:id="#+id/image_view">
android:layout_width="wrap_content"
android:src="#drawable/icon"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
ImageView>
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_toRightOf="#+id/image_view"
android:text="Relative layout">
TextView>
RelativeLayout>
But in case you have only text and image it is better to use
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#android:drawable/btn_image"
android:text="Button with Image"
android:gravity="left"
android:drawablePadding="10dp">
Button>
How you can access your widgets ?
This is very basic thing you have to know if you are developing for android, this is essential part. Please read documentation, read books, watch tutorial or whatever.
In short you need to inflate layout in activity onCreate() method
RelativeLayout mRelativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_root_layout);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
mRelativeLayout.setOnClickListener(.....)
}
But again this very basic things you must know.
You could set onClickListener for any of your views.
ImageView image = (ImageView) findViewById(R.id.image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Youractivity.this, Moveactivity.class));
}
});
Starting a new activity is done by creating an Intent and then calling startActivity, e.g.
Intent intent = new Intent(context, AnotherActivity.class);
context.startActivity(intent);
You can wrap this code in an OnClickListener as other answerers already suggested.
A second option is to add an android:onClick attribute to your RelativeLayout
<RelativeLayout ...
android:onClick="clickMe">
<ImageView .../>
<TextView .../>
</RelativeLayout>
and in your activity
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clickMe(View notused) {
Intent intent = new Intent(this, AnotherActivity.class);
this.startActivity(intent);
}
}
See startactivity for a complete example.
I've created a simplified example of the problem i've encountered. What i want is add a button to my fragment view when clicking on another button in the fragmentview.
Java
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imageView);
}
public void addSubmitButton(View view){
RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.activityLayout);
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
Button tv1 = new Button(this);
tv1.setText("Hello");
tv1.setLayoutParams(lparams);
rLayout.addView(tv1);
}
XML ActivityMain
<fragment
android:id="#+id/fragment"
tools:layout="#layout/fragment_main" />
XML fragment_main
<RelativeLayout
android:id="#+id/activityLayout"
tools:context=".MainActivityFragment">
<Button
android:id="#+id/button"
android:onClick="addSubmitButton" />
</RelativeLayout>
In the codes above I've removed not relevant code (like width height etc)
When i click the button onclick fires addSubmitButton, then the app crashes on a nullpointer for the line rLayout.addView(tv1); in addSubmitButton.
why is it null?
I think, this is not the correct way.
First, add the proper definition in your fragment view declaration in your activity's layout
android:name="com.example.android.fragments.MainActivityFragment"
You'd have to use a Fragment Manager to find the fragment populated into your activity. Once you have this fragment, you can get its view, in your case the RelativeLayout and then add the desired Button to this view.
The following might help:
FragmentManager fm = getFragmentManager();
fm.findFragmentById(R.id.yourFragmentId).getView().findViewById(R.id.activityLayout)
If you are using the support fragment use the getSupportFragmentManager()
Looks like you are missing the fully qualified name in your fragment element:
<fragment android:name="com.example.android.fragments.MyFragment"
android:id="#+id/fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
I have been trying for a while, and searching around a lot to figure this out, but no luck.
My problem is, in a nutshell: I can't set the Typeface of my Button programmatically. I can get it just fine with findViewById, and then I create my Typeface, and set it, nothing breaks everything seems normal. Except the change never shows up in the program. Its still the default typeface.
Here's my code.
public class MainActivity extends FragmentActivity {
Button lcb;
Typeface resoLite;
private SplashFragment splashFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
splashFragment = new SplashFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, splashFragment)
.commit();
} else {
// Or set the fragment from restored state info
splashFragment = (SplashFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
SpannableString s = new SpannableString("resocializer");
s.setSpan(new TypefaceSpan(this, "titillium-bold"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
// Update the action bar title with the TypefaceSpan instance
ActionBar actionBar = getActionBar();
//actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setTitle(s);
//Here's the important stuff. I get the button fine. I create the typeface
//fine. I set the typeface fine. but none of this appears to have any effect
//in the actual program when it's running.
lcb = (Button) findViewById(R.id.lcb);
resoLite = Typeface.createFromAsset(getAssets(), "fonts/titillium-bold.otf");
lcb.setTypeface(resoLite);
}
And my activity_main xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
<Button
android:id="#+id/lcb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/lcbText"
android:layout_gravity="center_horizontal"
android:layout_marginTop="60dp"
android:background="#C4A649"
android:textColor="#FFFFFF"
android:onClick="logConversation"/>
</LinearLayout>
I have tested the setTypeface with Logs and Typeface.equals() to check if it is setting to what I expect it to and it appears to be so. It just never changes in the actual button on the screen. I feel like there is something obvious I am missing. Any ideas?
EDIT: To be clear, I am trying to set the typeface to a custom font in my assets/fonts/ folder in the project, so setting it in the xml file won't work.
First place your font in the folder assets/fonts/your_font.ttf
Now in your Activity/Fragment class add these lines of code :
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/your_font.ttf");
Button custom_btn = (Button) findViewById(R.id.btn);
custom_btn.setTypeface(myTypeface);
custom_btn.setOnClickListener(this);