I am building and android app and have created the login screen. The next screen will show the logged in user a set of options from which he has to choose one.
The second activity is started from the onPostExecute method of an AsyncTask using the startActivity(intent) code.
Intent intent = null;
intent = new Intent(context, DisplayMessageActivity.class);
context.startActivity(intent);
I am trying to build the UI for this screen using the .xml file activity_display_message.xml. The entry for this has been made to the manifest file.
Any of the layout attributes that I am specifying in this .xml file are not getting applied. Any help in this regard is highly appreciated. For example using the code below I am unable to get the background color that I have set. This works fine with the .xml that I have for my main activity.
The onCreate function for my DisplayMessageActivity class is
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(CommonStaticValues.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
}
The complete activity_display_message.xml file is
<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:background="@color/background_color">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".DisplayMessageActivity" />
</RelativeLayout>
I see two problems here that are probably causing your problem. You first use
setContentViewlike this:That applied your XML file to the Activity, which is want you want. Later, you call it again with a
TextViewyou created locally. If you wanted anActivitythat consisted of oneTextViewon the screen, that’s one way to do it, but you don’t need it here because you have an XML definition of the Activity already.Secondly, your XML file’s
TextViewhas no android:id. That’s used to reference theTextViewfrom the code. So, modify your XML’sTextViewto add that like this:Then, back in your
onCreate, instead of constructing a newTextViewwithTextView textView = new TextView(this);, access theTextViewfrom the XML you applied like this:Notice that the argument for
findViewByIdis the id you create in the XML.