konstantin_doncov
konstantin_doncov

Reputation: 2879

LayoutInflater not displays the xml properly

I'm trying to use LayoutInflater for creating from xml layout some custom View.

MainActivity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.t1);

        Widget w = new Widget(getApplicationContext());

        layout.addView(w.getView());
    }

Widget:

 private Context context;
    public Widget(Context context) {
        this.context = context;
    }

    public View getView(){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.widget, null);
        ((Button)view.findViewById(R.id.button)).setText("button");
        ((TextView)view.findViewById(R.id.textView)).setText("text");

        return view;
    }

widget.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

But I got two problems:

  1. Activity displays only button without TextView.

  2. Button has black colour and white text, but in preview it has grey colour and black text.

How can I solve these problems?

Upvotes: 0

Views: 133

Answers (1)

P-Zenker
P-Zenker

Reputation: 355

Maybe you have to change your res/values/styles.xml params. With Android Studio 2.0 you can use the Theme Editor. Pretty nice if you don't need special buttons etc.

Or you can add custom colos for each view. For example add

android:textColor="@color/yourcolor1"
android:background="@color/yourcolor2"

to your text view. res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="yourcolor1">#FFFFFF</color>
 <color name="yourcolor2">#CCCCCC</color>
</resources>

Change your button attributes too like this (just examples):

android:textColor="@android:color/black"
android:background"@android:color/darker_gray"

Upvotes: 1

Related Questions