I am trying to create a horizontalscrollview in the onCreate() method of my first activity, since I want to make a large number of textviews to scroll through. Here is what I have so far:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout linscrollview;
HorizontalScrollView scrollview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollview = (HorizontalScrollView) findViewById(R.id.scrollview_layout);
linscrollview = new LinearLayout(this);
for(int i=0; i<5; i++) {
TextView tv = new TextView(this);
tv.setWidth(LayoutParams.WRAP_CONTENT);
tv.setHeight(LayoutParams.WRAP_CONTENT);
tv.setText("" + i);
tv.setTextSize(20);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
tv.setLayoutParams(params);
tv.setId(i);
linscrollview.addView(tv);
}
scrollview.addView(linscrollview);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I am not getting any errors, however no textviews are showing up.
Your problem is likely to do with the setWidth and setHeight methods. They set the exact value of the TextView width and height in pixels as described in the documentation:
Makes the TextView exactly this many pixels wide. You could do the same thing by specifying this number in the LayoutParams.
http://developer.android.com/reference/android/widget/TextView.html#setWidth(int)
What you want to do is set the LayoutParams for the TextView as you are already going slightly further down your code. So just get rid of those two method calls and it should work.