I'm trying to add multople TextViews to a relativeLayout on runtime.
the reason is that the list is to be created, depending on users choises.
I know how to add 1 textView. but when I entered the code to a loop and tried to creat more than 1, it just doesn't show anything..
pleas help,
int left=70,top=25;
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
EDIT: the full code of the activity:
package com.fgdvir.psychowords;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class WordTest extends Activity {
RelativeLayout testLayout;
int displayWidth, displayHeight;
ArrayList<String> startLetterPos = new ArrayList<String>();
//private int[] startLetterPos = new int[26];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.word_test);
startLetterPos = getIntent().getStringArrayListExtra("test");
testLayout = (RelativeLayout) findViewById(R.id.word_test);
create_questions();
// Get Screen size
/*
* Display display = getWindowManager().getDefaultDisplay(); Point size = new ` `Point(); display.getSize(size);
* displayWidth = size.x; displayHeight = size.y;
*/
}
public void create_questions() {
int left=70,top=25;
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (String s:startLetterPos){
params.leftMargin = left;
top += 70;
params.topMargin = top;
TextView tv = new TextView(this);
tv.setLayoutParams(params);
tv.setText(s);
tv.setVisibility(View.VISIBLE);
tv.setTextSize(20);
testLayout.addView(tv);
}
}
}
so I figured it out,
I still don't know why this doesn't work, but I found another way.
I added the text to a linearLayout, and then the linearLayout to my relative layout:
LinearLayout lL = new LinearLayout(this);
lL.setOrientation(LinearLayout.VERTICAL);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
, LayoutParams.WRAP_CONTENT);
for (int i = 0; i<26; i++){
String s = startLetterPos.get(i);
TextView tv = new TextView(this);
tv.setId(i);
tv.setText(s);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
if (i != 0 ){
params.addRule(RelativeLayout.BELOW, i-1);
}
lL.addView(tv,params);
}
testLayout.addView(lL);
}
Related
A sample code where i need to have a Edit Text in a Grid Layout Programatically .But when the text are entered in the app ,Only the small bottom portion of text is visible .The text is larger than expected. I need the edit text with text as shown in image which is Edit Text green background with only one line edit text required.Thanks
package com.example.myapplicationtesting;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridLayout;
public class MainActivity extends AppCompatActivity
{
#SuppressLint("ResourceType")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//LinearLayout linearLayout = findViewById(R.id.GroupContainer);
GridLayout Glyout;// = findViewById(R.id.Glayout_item);
Glyout = (GridLayout)findViewById(R.id.id_grid) ;
Glyout.setColumnCount(4);
Glyout.setRowCount(20);
int rowIndex = 0 ;
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = 50;//ViewGroup.LayoutParams.WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}
}
}
enter image description here
try setting param.height = 50; to WRAP_CONTENT
// Create EditText
for(int i = 0 ; i< 10 ; i++)
{
rowIndex = i ;
EditText editText = new EditText(this);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
param.height = WRAP_CONTENT;
param.width = 250 ;// GridLayout.LayoutParams.MATCH_PARENT;
param.rowSpec = GridLayout.spec(rowIndex);
param.columnSpec = GridLayout.spec(0);
param.setMargins(0,5,0,0);
editText.setTextColor(R.color.colorPrimaryDark);
editText.setTextSize(10);
editText.setBackgroundColor(0xFFFFFFFF);
editText.setLayoutParams(param);
if (rowIndex == 1) {
editText.setId( R.id.task1);
}
if (rowIndex == 2) {
editText.setId(R.id.task2);
}
//editText.setHeight(30);
// editText.setWidth(180);
// editText.setBackgroundColor(R.color.colorAccent);
Glyout.addView(editText);
rowIndex++;
}
I'm adding 5 elements in my CardView (ImageView, TextView and 3 buttons). I'm trying to set the RelativeLayout.LayoutParams and also adding the alignments in addRule() but somehow not getting the expected output.
This is my code:
package bhadra.com.mca;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Dashboard extends AppCompatActivity {
Button button_add, button_reports, button_appointment, button_message;
Context context;
CardView cardview;
ImageView imageview;
RelativeLayout.LayoutParams layoutparams, textparams, imageparams,
buttonparams, buttonparams2, buttonparams3;
TextView textview;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
button_add = (Button)findViewById(R.id.btn_add);
context = getApplicationContext();
linearLayout = (LinearLayout)findViewById(R.id.layout_linear);
//cardview = (CardView)findViewById(R.id.card_patientdetails);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createCardView();
}
});
}
public void createCardView() {
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,160 , getResources().getDisplayMetrics());
int margintop = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,30 , getResources().getDisplayMetrics());
int imglayout = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,60 , getResources().getDisplayMetrics());
int txtmargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,70 , getResources().getDisplayMetrics());
int drawpad = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5 , getResources().getDisplayMetrics());
int cardpad = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5 , getResources().getDisplayMetrics());
int cardpad2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10 , getResources().getDisplayMetrics());
int radius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,4 , getResources().getDisplayMetrics());
int elevation = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,10 , getResources().getDisplayMetrics());
cardview = new CardView(context);
layoutparams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, height);
layoutparams.setMargins(0,margintop,0,0);
imageparams = new RelativeLayout.LayoutParams(
imglayout, imglayout);
imageparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
textparams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
textparams.setMargins(0,txtmargin,0,0);
textparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonparams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
buttonparams2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonparams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
buttonparams2.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonparams3 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonparams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
buttonparams2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageview = new ImageView(context);
imageview.setLayoutParams(imageparams);
imageview.setImageResource(R.drawable.ic_account_circle_black_24px);
textview = new TextView(context);
textview.setLayoutParams(textparams);
textview.setText(R.string.patient_name);
textview.setTextSize(20);
textview.setTextColor(Color.BLACK);
button_reports = new Button(new ContextThemeWrapper(this, R.style.Widget_AppCompat_Button_Borderless), null, 0);
button_reports.setLayoutParams(buttonparams);
button_reports.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_assessment_black_24px, 0, 0, 0);
button_reports.setCompoundDrawablePadding(drawpad);
button_reports.setText(R.string.upload_reports);
button_reports.setTextSize(12);
button_appointment = new Button(new ContextThemeWrapper(this, R.style.Widget_AppCompat_Button_Borderless), null, 0);
button_appointment.setLayoutParams(buttonparams2);
button_appointment.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_today_black_24px, 0, 0, 0);
button_appointment.setCompoundDrawablePadding(drawpad);
button_appointment.setText(R.string.book_appointment);
button_appointment.setTextSize(12);
button_message = new Button(new ContextThemeWrapper(this, R.style.Widget_AppCompat_Button_Borderless), null, 0);
button_message.setLayoutParams(buttonparams3);
button_message.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_message_black_24px, 0, 0, 0);
button_message.setCompoundDrawablePadding(drawpad);
button_message.setText(R.string.message);
button_message.setTextSize(12);
cardview.setLayoutParams(layoutparams);
cardview.setRadius(radius);
cardview.setPadding(cardpad,cardpad2,cardpad, 0);
cardview.setMaxCardElevation(elevation);
cardview.addView(imageview);
cardview.addView(textview);
cardview.addView(button_reports);
cardview.addView(button_appointment);
cardview.addView(button_message);
linearLayout.addView(cardview);
}
}
This code is giving me the following output:
Output
Can someone please help me?
I have the following class which generates a calendar view. I'm not too fond of the built-in one, and am trying to gain more control over its appearance. However rendering the new UI (e.g. upon swipe) is taking 1-2 seconds to draw. Is there any place I could speed this up? Am testing on HTC One S (2012 model)
Should be relatively straightforward to follow:
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.joda.time.LocalDate;
import java.util.ArrayList;
public class Calendar extends AppCompatActivity {
private LocalDate _currentSelectedDate = new LocalDate();;
private LocalDate _today = new LocalDate();;
private float x1 = 0;
private float x2 = 0;
private float y1 = 0;
private float y2 = 0;
private TableLayout _tableLayout;
private RelativeLayout _relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
_relativeLayout = (RelativeLayout) findViewById(R.id.calendarLayout);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
#Override
public boolean onTouchEvent(MotionEvent touchevent)
{
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
// up
if (y1 > y2)
{
_currentSelectedDate = _currentSelectedDate.plusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
// down
if (y1 < y2)
{
_currentSelectedDate = _currentSelectedDate.minusMonths(1);
recreateUI(_currentSelectedDate.getYear(), _currentSelectedDate.getMonthOfYear());
}
break;
}
}
return false;
}
private void recreateUI(int year, int month)
{
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
_tableLayout = new TableLayout(this);
_tableLayout.setLayoutParams(lp);
_tableLayout.setStretchAllColumns(true);
_relativeLayout.removeAllViews();
_relativeLayout.addView(_tableLayout);
LocalDate date = new LocalDate().withYear(year).withMonthOfYear(month).dayOfMonth().withMinimumValue();
LocalDate last = date.dayOfMonth().withMaximumValue();
addMonthNameToUi(date);
addDaysNamesToUi();
addDayNumberssToUi(date, last);
}
private void addMonthNameToUi(LocalDate date) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT);
params.span = 7;
TextView t = new TextView(this);
t.setLayoutParams(params);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
t.setText(date.toString("MMM yyyy"));
row.addView(t);
float d = getResources().getDisplayMetrics().density;
int margin = (int)(20 * d);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) t.getLayoutParams();
mlp.setMargins(mlp.leftMargin, mlp.topMargin, mlp.rightMargin, margin);
_tableLayout.addView(row);
}
private void addDaysNamesToUi() {
TableRow dayNameRow = new TableRow(this);
addMonth(dayNameRow, "Mon");
addMonth(dayNameRow, "Tue");
addMonth(dayNameRow, "Wed");
addMonth(dayNameRow, "Thu");
addMonth(dayNameRow, "Fri");
addMonth(dayNameRow, "Sat");
addMonth(dayNameRow, "Sun");
_tableLayout.addView(dayNameRow);
}
private void addDayNumberssToUi(LocalDate date, LocalDate last) {
TableRow row = null;
int columnsCount = 0;
boolean firstRow = true;
while (date.isBefore(last) || date.isEqual(last)) {
if (columnsCount == 0) {
row = new TableRow(this);
_tableLayout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT, 1.0f));
// blank columns for days not at the start of month
if (firstRow) {
firstRow = false;
int i = 1;
for (; i < date.getDayOfWeek(); i++) {
addDayNumberToRow(row, date, "");
}
columnsCount += i - 1;
date.plusDays(i - 1);
}
}
addDayNumberToRow(row, date, String.valueOf(date.getDayOfMonth()));
date = date.plusDays(1);
columnsCount++;
if (columnsCount == 7)
columnsCount = 0;
}
while (row.getChildCount() < 7)
addDayNumberToRow(row, date, "");
}
private void addMonth(TableRow row, String month)
{
TextView t = new TextView(this);
t.setText(month);
t.setGravity(Gravity.CENTER);
t.setTypeface(null, Typeface.BOLD);
row.addView(t);
}
private void addDayNumberToRow(TableRow row, final LocalDate date, String text)
{
TextView v = new TextView(this);
v.setText(text);
v.setGravity(Gravity.CENTER);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));
if (date.getDayOfMonth() == _today.getDayOfMonth() && date.getMonthOfYear() == _today.getMonthOfYear() && date.getYear() == _today.getYear()) {
v.setTypeface(v.getTypeface(), Typeface.BOLD);
v.setTextSize(v.getTextSize() + 1);
}
ShapeDrawable border = new ShapeDrawable(new RectShape());
border.getPaint().setStyle(Paint.Style.STROKE);
border.getPaint().setColor(Color.BLACK);
v.setBackground(border);
row.addView(v);
}
}
Your "recreateUI" method do alot of stuff like creating new views. Avoid creating new objects by reusing those already created.
Usually calendar views are quite complex. You most likely wont achieve smooth framerate by using multiple views in such way. You would have to write custom view witch will draw itself.
Turns out a lot of the slowdown was caused from running the application under debug mode -- running it normally resulted in acceptable performance.
I am trying to achieve a layout dynamically which is given below:
I can manage to done all things dynamically. But I can't align item name (Chicken Masala) to right of the ImageView . I am reached at this position as following.
RelativeLayout primary_layout = new RelativeLayout(this);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
primary_layout.setLayoutParams(layoutParam);
// primary_layout.setOrientation(LinearLayout.HORIZONTAL);
// primary_layout.setBackgroundColor(0xff99ccff);
//String cross = " � ";
String makeString = aOrder.getQuantity() + " "
+ aOrder.getFoodName();
ImageView imageView_remove = createAImageview(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.CENTER_VERTICAL,
10, 20);
TextView item_name = createATextViewWithParam(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_TOP, imageView_remove.getId(),
makeString, 20, 10, 20);
TextView txt_item_price = createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
"" + item_price, 20, 10, 20);
primary_layout.addView(imageView_remove);
primary_layout.addView(item_name);
primary_layout.addView(txt_item_price);
I am share Two methods createAImageview() & createATextViewWithParam() which is necessary for this Layout.
public ImageView createAImageview(int layout_width, int layout_height, int align,
int margin, int padding) {
ImageView imageView = new ImageView(this);
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_width, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
imageView.setLayoutParams(_params);
imageView.setPadding(padding, padding, padding, padding);
imageView.setImageResource(R.mipmap.remove);
return imageView;
}
public TextView createATextViewWithParam(int layout_widh, int layout_height, int align, int align_id,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align, align_id);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}
You need to add rule for LEFT_OF/RIGHT_OF :
_params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
_params.addRule(RelativeLayout.LEFT_OF, R.id.id_of_textview);
imageView.setLayoutParams(_params);
Try this,
activity_main.xml
<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"
tools:context="com.example.dynamicviewdemo.MainActivity" >
<RelativeLayout
android:id="#+id/llAddMember"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical" />
</RelativeLayout>
MainActivity.java
package com.example.dynamicviewdemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
private RelativeLayout llAddMember;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
llAddMember = (RelativeLayout) findViewById(R.id.llAddMember);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
final RelativeLayout linearLayout = new RelativeLayout(getApplicationContext());
linearLayout.setLayoutParams(layoutParams);
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ImageView imgView = new ImageView(MainActivity.this);
imgView.setImageResource(R.drawable.ic_launcher);
imgView.setLayoutParams(lparams);
linearLayout.addView(imgView);
lparams.setMargins(0, 15, 0, 0);
LayoutParams lparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView txtResGender = new TextView(MainActivity.this);
txtResGender.setLayoutParams(lparams1);
txtResGender.setText("Hello World");
txtResGender.setTextSize(14);
txtResGender.setTextColor(Color.parseColor("#9C9C9C"));
linearLayout.addView(txtResGender);
lparams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lparams1.setMargins(0, 30, 15, 0);
llAddMember.addView(linearLayout);
}
}
I have a tablelayout in an activity which contains header(column name), middle layout(column data) and a footer (button). Now i need a vertical scroll for middle layout and horizontal scroll for header and middle layout.
The vertical scroll for middle layout works fine but horizontal scroll is not working.
How can i add both way scroll in a single activity programmatically without using xml?
Here is my code so far.
RelativeLayout rlBody = new RelativeLayout(this);
rlBody.setPadding(0, 0, 0, 0);
RelativeLayout.LayoutParams bodyParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
rlBody.setLayoutParams(bodyParams);
but_downl = new Button(getApplicationContext());
but_downl.setText("Download");
but_downl.setWidth(width);
RelativeLayout footer = new RelativeLayout(this);
RelativeLayout.LayoutParams footerParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
footerParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
footer.setLayoutParams(footerParams);
footer.addView(but_downl);
RelativeLayout rlmaintableLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams rlmaintableLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
rlmaintableLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rlmaintableLayoutParams.addRule(RelativeLayout.ABOVE, footer.getId());
rlmaintableLayout.setLayoutParams(rlmaintableLayoutParams);
TableLayout maintableLayout = new TableLayout(getApplicationContext());
maintableLayout.setVerticalScrollBarEnabled(true);
TextView tvQnr, tvDownLType, tvPublishBy, tvPublishDate, tvMonPlan, tvLang, textViewMsg;
CheckBox chk, chkparent;
View v;
tableRow = new TableRow(getApplicationContext());
v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
chkparent=new CheckBox(this);
tableRow.addView(chkparent);
tvQnr=new TextView(getApplicationContext());
tvQnr.setText("Name");
tvQnr.setTextColor(Color.parseColor("#235C8B"));
tvQnr.setTypeface(null, Typeface.BOLD);
tvQnr.setTextSize(20);
tvQnr.setPadding(20, 20, 30, 20);
tableRow.addView(tvQnr);
tvDownLType=new TextView(getApplicationContext());
tvDownLType.setText("Age");
tvDownLType.setTextColor(Color.parseColor("#235C8B"));
tvDownLType.setTypeface(null, Typeface.BOLD);
tvDownLType.setTextSize(20);
tvDownLType.setPadding(20, 20, 20, 20);
tableRow.addView(tvDownLType);
tvPublishBy=new TextView(getApplicationContext());
tvPublishBy.setText("Gender");
tvPublishBy.setTextColor(Color.parseColor("#235C8B"));
tvPublishBy.setTypeface(null, Typeface.BOLD);
tvPublishBy.setTextSize(20);
tvPublishBy.setPadding(20, 20, 20, 20);
tableRow.addView(tvPublishBy);
tvPublishDate=new TextView(getApplicationContext());
tvPublishDate.setText("Published Date");
tvPublishDate.setTextColor(Color.parseColor("#235C8B"));
tvPublishDate.setTypeface(null, Typeface.BOLD);
tvPublishDate.setTextSize(20);
tvPublishDate.setPadding(20, 20, 20, 20);
tableRow.addView(tvPublishDate);
tvMonPlan=new TextView(getApplicationContext());
tvMonPlan.setText("Roll No");
tvMonPlan.setTextColor(Color.parseColor("#235C8B"));
tvMonPlan.setTypeface(null, Typeface.BOLD);
tvMonPlan.setTextSize(20);
tvMonPlan.setPadding(20, 20, 20, 20);
tableRow.addView(tvMonPlan);
tvLang=new TextView(getApplicationContext());
tvLang.setText("Language");
tvLang.setTextColor(Color.parseColor("#235C8B"));
tvLang.setTypeface(null, Typeface.BOLD);
tvLang.setTextSize(20);
tvLang.setPadding(20, 20, 20, 20);
tableRow.addView(tvLang);
maintableLayout.addView(tableRow);
maintableLayout.addView(v);
RelativeLayout scrollHolder = new RelativeLayout(this);
RelativeLayout.LayoutParams scrollHolderParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
scrollHolder.setLayoutParams(scrollHolderParams);
ScrollView myScrollView = new ScrollView(this);
myScrollView.setEnabled(true);
HorizontalScrollView horscrollview = new HorizontalScrollView(this);
horscrollview.setEnabled(true);
TableLayout tableLayout = new TableLayout(getApplicationContext());
int cnt = 0;
for (int j = 0; j < myFormresult.size(); j++){
tableRow = new TableRow(getApplicationContext());
v = new View(this);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
cnt = cnt + 1;
chk = new CheckBox(this);
tvQnr = new TextView(getApplicationContext());
tvQnr.setTextColor(Color.parseColor("#235C8B"));
tvQnr.setTextSize(15);
tvQnr.setText(myFormresult.get(j).getFormName());
tvQnr.setPadding(25, 10, 20, 10);
tvDownLType = new TextView(getApplicationContext());
tvDownLType.setTextColor(Color.parseColor("#235C8B"));
tvDownLType.setTextSize(15);
tvDownLType.setText(myFormresult.get(j).getVersion());
tvDownLType.setPadding(25, 10, 20, 10);
tvPublishBy = new TextView(getApplicationContext());
tvPublishBy.setTextColor(Color.parseColor("#235C8B"));
tvPublishBy.setTextSize(15);
tvPublishBy.setText(myFormresult.get(j).getPublishedBy());
tvPublishBy.setPadding(25, 10, 20, 10);
tvPublishDate = new TextView(getApplicationContext());
tvPublishDate.setTextColor(Color.parseColor("#235C8B"));
tvPublishDate.setTextSize(15);
tvPublishDate.setText(myFormresult.get(j).getPublishedDate());
tvPublishDate.setPadding(25, 10, 20, 10);
tvMonPlan = new TextView(getApplicationContext());
tvMonPlan.setTextColor(Color.parseColor("#235C8B"));
tvMonPlan.setTextSize(15);
tvMonPlan.setText(myFormresult.get(j).getMonitoringPlan());
tvMonPlan.setPadding(25, 10, 20, 10);
tvLang = new TextView(getApplicationContext());
tvLang.setTextColor(Color.parseColor("#235C8B"));
tvLang.setTextSize(15);
tvLang.setText(myFormresult.get(j).getLanguage());
tvLang.setPadding(25, 10, 20, 10);
tableRow.addView(chk);
tableRow.addView(tvQnr);
tableRow.addView(tvDownLType);
tableRow.addView(tvPublishBy);
tableRow.addView(tvPublishDate);
tableRow.addView(tvMonPlan);
tableRow.addView(tvLang);
tableLayout.addView(tableRow);
tableLayout.addView(v);
tableLayout.addView(vertView);
}
if (cnt == 0) {
textViewMsg = new TextView(getApplicationContext());
textViewMsg.setText("No records found ...");
textViewMsg.setTextColor(Color.parseColor("#235C8B"));
textViewMsg.setTextSize(15);
tableLayout.addView(textViewMsg);
but_downl.setEnabled(false);
}
myScrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
horscrollview.addView(tableLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
myScrollView.addView(horscrollview);
scrollHolder.addView(myScrollView);
maintableLayout.addView(scrollHolder);
rlmaintableLayout.addView(maintableLayout);
rlBody.addView(rlmaintableLayout);
rlBody.addView(footer);
Thanks in advance ...
I was created table layout with horizontal and vertical scrolling. Also header is fixed at vertical scrolling.
I sent you code of class and xml file you can customize it according your requirement.
I hope it will help you.
Create MainActivity Class:
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
HorizontalScrollView hori,hori2;
int viewWidth;
TableLayout scrollablePart;
GestureDetector gestureDetector = null;
ArrayList<LinearLayout> layouts;
LinearLayout linear;
private int scrollMax;
int currPosition, prevPosition;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TableRow.LayoutParams wrapWrapTableRowParams = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int[] fixedColumnWidths = new int[]{20, 20, 20, 20, 20, 20};
int[] scrollableColumnWidths = new int[]{20,20, 20, 20, 20, 20};
int fixedRowHeight = 50;
int fixedHeaderHeight = 60;
TableRow row = new TableRow(this);
//header (fixed horizontally)
TableLayout fixedColumn = (TableLayout) findViewById(R.id.fixed_column);
TableLayout fixedColumn2 = (TableLayout) findViewById(R.id.fixed_header_column);
TextView fixedView2 = makeTableRowWithText("col 1 ", scrollableColumnWidths[0], fixedRowHeight);
fixedView2.setBackgroundColor(Color.LTGRAY);
fixedColumn2.addView(fixedView2);
//rest of the table (within a scroll view)
scrollablePart = (TableLayout) findViewById(R.id.scrollable_part);
//header (fixed vertically)
hori=(HorizontalScrollView)findViewById(R.id.horizon);
hori.setVerticalScrollBarEnabled(false);
hori.setHorizontalScrollBarEnabled(false);
hori2=(HorizontalScrollView)findViewById(R.id.hr_2);
//hori.onScrollChanged
hori2.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
moveScrollView();
cal();
//startAutoScrolling();
return false;
}
});
ScrollView scrol=(ScrollView)findViewById(R.id.Scroll);
//scrol.onScrollChanged(fixedHeaderHeight, fixedHeaderHeight, fixedHeaderHeight, fixedHeaderHeight);
linear=(LinearLayout)findViewById(R.id.fillable_area);
TableLayout header = (TableLayout) findViewById(R.id.table_header);
//scrollablePart.onGenericMotionEvent(MotionEvent.ACTION_MOVE);
ViewTreeObserver vto = linear.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
linear.getViewTreeObserver().removeGlobalOnLayoutListener(this);
getScrollMaxAmount();
}
});
hori2.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
moveScrollView();
//startAutoScrolling();
return false;
}
});
row.setLayoutParams(wrapWrapTableRowParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(Color.GRAY);
row.addView(makeTableRowWithText("col 2", fixedColumnWidths[1], fixedHeaderHeight));
row.addView(makeTableRowWithText("col 3", fixedColumnWidths[2], fixedHeaderHeight));
row.addView(makeTableRowWithText("col 4", fixedColumnWidths[3], fixedHeaderHeight));
row.addView(makeTableRowWithText("col 5", fixedColumnWidths[4], fixedHeaderHeight));
row.addView(makeTableRowWithText("col 6", fixedColumnWidths[5], fixedHeaderHeight));
header.addView(row);
for(int i = 0; i < 50; i++)
{
TextView fixedView = makeTableRowWithText("row number " + i, scrollableColumnWidths[0], fixedRowHeight);
fixedView.setBackgroundColor(Color.BLUE);
fixedColumn.addView(fixedView);
row = new TableRow(this);
row.setLayoutParams(wrapWrapTableRowParams);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(Color.WHITE);
row.addView(makeTableRowWithText("value 2", scrollableColumnWidths[1], fixedRowHeight));
row.addView(makeTableRowWithText("value 3", scrollableColumnWidths[2], fixedRowHeight));
row.addView(makeTableRowWithText("value 4", scrollableColumnWidths[3], fixedRowHeight));
row.addView(makeTableRowWithText("value 5", scrollableColumnWidths[4], fixedRowHeight));
row.addView(makeTableRowWithText("value 6", scrollableColumnWidths[5], fixedRowHeight));
scrollablePart.addView(row);
}
}
private void cal(){
final Handler handler2 = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run()
{
if(i==0)
{
try{
moveScrollView();
}catch (Exception e){
}
i++;
}
handler2.postDelayed(this,500);
}
};
handler2.postDelayed(runnable, 500);
}
public void getScrollMaxAmount(){
int actualWidth = (linear.getMeasuredWidth()-512);
scrollMax = actualWidth;
System.out.println("scrollMax"+scrollMax);
}
private Timer scrollTimer = null;
private Timer clickTimer = null;
private Timer faceTimer = null;
private TimerTask clickSchedule;
private TimerTask scrollerSchedule;
private TimerTask faceAnimationSchedule;
private int scrollPos = 0;
public void startAutoScrolling(){
if (scrollTimer == null) {
scrollTimer = new Timer();
final Runnable Timer_Tick = new Runnable() {
public void run() {
moveScrollView();
}
};
if(scrollerSchedule != null){
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask(){
#Override
public void run(){
runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 30, 30);
}
}
public void moveScrollView(){
scrollPos = (int) (hori.getScrollX() + 1.0);
scrollPos = (int) (hori2.getScrollX() + 1.0);
System.out.println("scrollPos"+scrollPos);
if(scrollPos >= scrollMax){
scrollPos = 0;
}
hori2.scrollTo(scrollPos, 0);
hori.scrollTo(scrollPos, 0);
}
private TextView recyclableTextView;
public TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth, int fixedHeightInPixels) {
int screenWidth = getResources().getDisplayMetrics().widthPixels;
recyclableTextView = new TextView(this);
recyclableTextView.setText(text);
recyclableTextView.setTextColor(Color.BLACK);
recyclableTextView.setTextSize(20);
recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);
recyclableTextView.setHeight(fixedHeightInPixels);
return recyclableTextView;
}
}
Create activity_main.xmml like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:id="#+id/fillable_area">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:gravity="center_horizontal"
android:id="#+id/fillable_area1">
<TableLayout
android:id="#+id/fixed_header_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<HorizontalScrollView
android:id="#+id/horizon"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/table_header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</HorizontalScrollView>
</LinearLayout>
<ScrollView
android:id="#+id/Scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:id="#+id/fillable_area">
<TableLayout
android:id="#+id/fixed_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<HorizontalScrollView
android:id="#+id/hr_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableLayout
android:id="#+id/scrollable_part"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</HorizontalScrollView>
</LinearLayout>
</ScrollView>