Thursday, March 5, 2020

How to change ActionBar title in Android

Create layout activity_main.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#d0d8ed"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change ActionBar Title Font"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>
Step 2. MainActivity.java created
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActionBar ab = getActionBar();
                TextView tv = new TextView(getApplicationContext());
                LayoutParams lp = new RelativeLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT,
                        LayoutParams.WRAP_CONTENT);
                tv.setLayoutParams(lp);
                tv.setText(ab.getTitle());
                tv.setTextColor(Color.BLACK);
                tv.setTypeface(Typeface.MONOSPACE);
                ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
                ab.setCustomView(tv);
            }
        });
    }
}
How to change ActionBar

No comments:

Post a Comment