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:
Activity displays only button without TextView.
Button has black colour and white text, but in preview it has grey colour and black text.
How can I solve these problems?