How to add a custom class that extends the view to the main?

I'm having problems adding a custom class to my main activity.

in my custom class:

public class DetailView extends View { public DetailView(Context context) { super(context); this.setBackgroundColor(0xFF00FF00 ); } } 

in the main activity:

 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); linearLayout = (LinearLayout) findViewById(R.id.linearLayout1); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); linearLayout.setOrientation(LinearLayout.VERTICAL); txt = new TextView(this); txt.setText("hello"); txt.setId(6); txt.setLayoutParams(params); linearLayout.addView(txt); DetailView detailView = new DetailView(this.getApplicationContext()); linearLayout.addView(detailView); } 

Why can’t I see the detailView? I'm new to Android development, so I need any help I can get, or good links or something else. Thanks

+6
source share
1 answer

A view has been added, but it does not have a set of dimensions. Looking at existing code, I think you want it to fill the width and have a small height - just assuming. So try the following:

 DetailView detailView = new DetailView(this); params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2); // 2 pixels height linearLayout.addView(detailView, params); 

In addition, the DetailView context is an action, not an application context.

+3
source

Source: https://habr.com/ru/post/954233/


All Articles