Sometimes you are invited to update the string label of your title bar activity at runtime.
To do this, we start by adding a new xml file of the custom view to be use as a new layout for the title bar view.
We use in this example a textView view to update the title's string.
In the main.xml file, we use an EditView and a Button to simulate the update of the Acitivity title label.
Finally, in your Java file use the Window.setfeatureInt method to apply the new layout to the title bar view.
To do this, we start by adding a new xml file of the custom view to be use as a new layout for the title bar view.
We use in this example a textView view to update the title's string.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/custom_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" /> </RelativeLayout>
In the main.xml file, we use an EditView and a Button to simulate the update of the Acitivity title label.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/screen" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="10px" android:baselineAligned="false" > <EditText android:id="@+id/edit_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxEms="10" android:minEms="10" android:layout_gravity="center_vertical" android:text="@string/custom_title_edit" /> <Button android:id="@+id/change_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="@string/custom_title_button"/> </LinearLayout>
Finally, in your Java file use the Window.setfeatureInt method to apply the new layout to the title bar view.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
final TextView customText = (TextView) findViewById(R.id.custom_text);
final EditText textEdit = (EditText) findViewById(R.id.edit_text);
Button Change_button = (Button) findViewById(R.id.change_button);
Change_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
customText.setText(textEdit.getText());
}
});
}
Good job!
ReplyDelete