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>
Related
I'm creating a ScrollView, nesting in a RelativeLayout (which contains tables). Everything is properly added to the layout. The problem is: vertically scrolling works fine, but horizontal scrolling does NOT work at all. I already tested various combinations of MATCH_PARENT, WRAP_CONTENT and FILL_PARENT. No try even worked close. So my question is: What am I missing here?
Here is the code:
public class PlayerView extends View {
private RelativeLayout relativeLayout;
private TableLayout tableLayout;
private int player_loop;
private int player_count;
public PlayerView(Context context, int player_count){
super(context);
setPlayer_count(player_count);
}
public ScrollView create_scrollView(){
ScrollView scrollView = new ScrollView(getContext());
ScrollView.LayoutParams scroll_params = new ScrollView.LayoutParams(
ScrollView.LayoutParams.MATCH_PARENT,
ScrollView.LayoutParams.MATCH_PARENT
);
scrollView.setLayoutParams(scroll_params);
scrollView.addView(create_relativeLayout());
return scrollView;
}
public RelativeLayout create_relativeLayout(){
relativeLayout = new RelativeLayout(getContext());
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
relativeLayout.setLayoutParams(relativeParams);
create_Player_Table_Layout();
return relativeLayout;
}
public void create_Player_Table_Layout(){
for(player_loop = 1; player_loop <= player_count; player_loop++){
relativeLayout.addView(player_table(getResources().getString(R.string.dummy_player_name) + player_loop, player_loop));
}
}
public TableLayout player_table(String playername, int playernumber){
tableLayout = new TableLayout(getContext());
tableLayout.setId(playernumber * 1000);
if (playernumber > 1) {
//TABLE PLACEMENT
RelativeLayout.LayoutParams tbl_params_New = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
tbl_params_New.addRule(RelativeLayout.RIGHT_OF, (playernumber - 1) * 1000);
tableLayout.setLayoutParams(tbl_params_New);
}
//Add Playername
TableRow row_playername = new TableRow(getContext());
TextView view_name = new TextView(getContext());
TableRow.LayoutParams view_name_params = new TableRow.LayoutParams();
view_name_params.setMargins(20,20,20,20);
view_name.setLayoutParams(view_name_params);
view_name.setGravity(Gravity.CENTER);
view_name.setText(playername);
view_name.setTextSize(20);
view_name.setId(playernumber * 100);
row_playername.addView(view_name);
tableLayout.addView(row_playername);
//Add Lifepoints
TableRow row_lifepoints = new TableRow(getContext());
TextView view_lifepoints = new TextView(getContext());
TableRow.LayoutParams view_lifepoints_params = new TableRow.LayoutParams();
view_lifepoints_params.setMargins(20, 0, 20, 20);
view_lifepoints.setText("40");
view_lifepoints.setTextSize(40);
view_lifepoints.setGravity(Gravity.CENTER);
view_lifepoints.setId(playernumber * 100 + 10);
view_lifepoints.setLayoutParams(view_lifepoints_params);
row_lifepoints.addView(view_lifepoints);
tableLayout.addView(row_lifepoints);
Log.d("Test", "Player count:" + player_count);
for(int opponent_loop = 1; opponent_loop <= player_count; opponent_loop++){
tableLayout.addView(commander_damage_from_player(player_loop, opponent_loop));
}
return tableLayout;
}
private TableRow commander_damage_from_player(int player_loop, int opponent_loop){
TableRow row = new TableRow(getContext());
TextView textView = new TextView(getContext());
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
layoutParams.setMargins(20, 0, 40, 20);
textView.setLayoutParams(layoutParams);
textView.setText("0 | " + getResources().getString(R.string.dummy_player_name)+ " " + opponent_loop);
textView.setTextSize(20);
textView.setId(player_loop + 100 + opponent_loop);
row.addView(textView);
return row;
}
private void setPlayer_count(int player_count){
this.player_count = player_count;
}
}
And for documentation the calling class:
public class Home extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PlayerView playerView = new PlayerView(this, 8);
setContentView(playerView.create_scrollView());
}
}
The only way you can do this is by creating a horizontalscrollview to be the child of the scrollview. If you make the minor modification to your create_relativeLayout() to create a horizontalscroll view then it will work correctly. I have seen this happen in other examples.
public HorizontalScrollView create_relativeLayout(){
HorizontalScrollView horizontalScrollView = new HorizontalScrollView(getContext());
relativeLayout = new RelativeLayout(getContext());
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT
);
relativeLayout.setLayoutParams(relativeParams);
create_Player_Table_Layout();
horizontalScrollView.addView(relativeLayout);
return horizontalScrollView;
}
The application it works well but after I put 'setContentView(R.layout.activity_main)' in my class to set the content and the to show a image is telling me that error:
android.view.InflateException: Binary XML file line #2: Error inflating class android.support.design.widget.CoordinatorLayout
I am inheritance from AndARActivity to make a simple app for marker recognistion.
The XML with problem is this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="webdata.com.mascotcollector.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
What I am doing wrong?
Make sure you have the correct dependency in your gradle file
compile 'com.android.support:design:25.0.1'
The MainActivity.java (setContentView(R.layout.activity_main); is the instruction with problem):
package webdata.com.mascotcollector;
/**
* Created by ilie on 11.11.2016.
*/
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Random;
import edu.dhbw.andar.ARToolkit;
import edu.dhbw.andar.AndARActivity;
import edu.dhbw.andar.exceptions.AndARException;
public class MainActivity extends AndARActivity {
private static final String TAG = "MainActivity";
private View m_RootLayout;
private TextView m_MessageTextView;
private TextView m_XPosLabel;
private TextView m_YPosLabel;
private TextView m_ZPosLabel;
private TextView m_MarkerNameLabel;
private TextView m_ScorePosLabel;
private TextView m_XPosValue;
private TextView m_YPosValue;
private TextView m_ZPosValue;
private TextView m_MarkerNameValue;
private TextView m_ScorePosValue;
private ARToolkit m_ARToolkit;
private Cube[] cubesArr = new Cube[6];
private Utils utils = new Utils();
private double[] centerMarker = {0, 0};
private float[] grayColor = {0.5f, 0.5f, 0.5f, 1.0f},
redColor = {1.0f, 0f, 0f, 1.0f},
yellowColor = {1.0f, 0.8f, 0.0f, 1.0f},
greenColor = {0.0f, 0.6f, 0.0f, 1.0f},
blackColor = {0.0f, 0.0f, 0.0f, 1.0f};
private double markerWidth = 80.0;
int score = 0;
private Random rand = new Random();
private int randInt = 0;
ImageView mImageView;
// Dupa ce se elibereaza click-ul lung, se intra pe un click scurt, ceea ce necesita
// introducerea unei variabile de control (false - click lung; true - click scurt)
private boolean longClick = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_RootLayout = findViewById(android.R.id.content);
//m_RootLayout.setOnTouchListener(this);
//setContentView(R.layout.activity_main);
m_RootLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
longClick = true;
for (int i = 0; i < cubesArr.length; i++) {
if (cubesArr[i].isVisible() && cubesArr[i].getMarkerName().equals(m_MarkerNameValue.getText().toString())) {
if (cubesArr[i].getColor() != blackColor) {
// Daca nu este o capcana stabilita anterior, atunci transforma cubul in capcana.
cubesArr[i].setTrap(true);
cubesArr[i].setColor(blackColor);
} else {
// Daca este o capcana stabilita anterior, atunci scade punctajul jucatorului si
// elimina capcana.
score -= 20;
cubesArr[i].setTrap(false);
cubesArr[i].setColor(grayColor);
System.out.println("A fost o capcana stabilita anterior!");
}
}
}
return false;
}
});
m_RootLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (longClick == false) {
for (int i = 0; i < cubesArr.length; i++) {
if (cubesArr[i].isVisible() && cubesArr[i].getMarkerName().equals(m_MarkerNameValue.getText().toString())) {
if (!cubesArr[i].isTrap()) {
// Daca nu este capcana, la o atingere a cubului stabileste un punctaj pentru
// jucator in functie de culoarea care iese.
if (cubesArr[i].getColor() == grayColor) {
randInt = rand.nextInt(3);
if (randInt == 2) {
cubesArr[i].setColor(greenColor);
score += 5;
} else if (randInt == 1) {
cubesArr[i].setColor(yellowColor);
} else {
cubesArr[i].setColor(redColor);
score -= 5;
}
}
} else {
// Daca este o capcana, scade punctajul jucatorului cu 20 de unitati.
score -= 20;
cubesArr[i].setTrap(false);
cubesArr[i].setColor(grayColor);
System.out.println("A fost o capcana!");
}
}
}
}
else {
System.out.println("ESTE LONG");
longClick = false;
}
}
});
CreateLayout((FrameLayout)m_RootLayout);
CustomRenderer renderer = new CustomRenderer();
setNonARRenderer(renderer);
//mImageView.setImageResource(R.drawable.pisica);
try {
m_ARToolkit = getArtoolkit();
cubesArr[0] = new Cube("ACS_Cube", "marker16_acs.patt", markerWidth, centerMarker, grayColor, "marker16_acs.patt");
cubesArr[1] = new Cube("ARTest_Cube", "marker16_artest.patt", markerWidth, centerMarker, grayColor, "marker16_artest.patt");
cubesArr[2] = new Cube("DSRV_Cube", "marker16_dsrv.patt", markerWidth, centerMarker, grayColor, "marker16_dsrv.patt");
cubesArr[3] = new Cube("UPB_Cube", "marker16_upb.patt", markerWidth, centerMarker, grayColor, "marker16_upb.patt");
cubesArr[4] = new Cube("Cube_1", "marker16_cube1.patt", markerWidth, centerMarker, grayColor, "marker16_cube1.patt");
cubesArr[5] = new Cube("Cube_2", "marker16_cube2.patt", markerWidth, centerMarker, grayColor, "marker16_cube2.patt");
for (int i = 0; i < cubesArr.length; i++) {
m_ARToolkit.registerARObject(cubesArr[i]);
}
} catch (AndARException ex) {
Log.e(TAG, "AndAR EXCEPTION: " + ex.getMessage());
}
startPreview();
new Thread(new Runnable() {
public void run() {
while(true) {
try {
Thread.sleep(30);
m_RootLayout.post(new Runnable() {
public void run() {
boolean objectVisible = false;
for (int i = 0; i < cubesArr.length; i++) {
if (cubesArr[i].isVisible()) {
objectVisible = utils.chkCube(cubesArr[i], objectVisible,
m_XPosValue, m_YPosValue, m_ZPosValue, m_MarkerNameValue, m_MessageTextView);
} else {
if (!cubesArr[i].isTrap()) {
cubesArr[i].setColor(grayColor);
} else {
cubesArr[i].setColor(blackColor);
}
}
}
if (!objectVisible) {
m_XPosValue.setText(R.string.emptyString);
m_YPosValue.setText(R.string.emptyString);
m_ZPosValue.setText(R.string.emptyString);
m_MarkerNameValue.setText(R.string.emptyString);
m_MessageTextView.setText("");
}
m_ScorePosValue.setText(String.valueOf(score));
}
});
} catch (Exception e) {
System.out.println("EXCEPTION !!!");
}
}
}
}).start();
//setContentView(R.layout.content_main);
//TODO: de revizuit activity_main.xml
setContentView(R.layout.activity_main);
//mImageView = (ImageView) findViewById(R.id.imageView);
//mImageView.setImageResource(R.drawable.pisica);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
}
private void CreateLayout(FrameLayout rootLayout) {
float densityDpi = this.getResources().getDisplayMetrics().density;
int marginPixel = (int)densityDpi*5;
LinearLayout labelsLayout = new LinearLayout(this);
LinearLayout.LayoutParams layoutParamsRoot = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
labelsLayout.setOrientation(LinearLayout.VERTICAL);
labelsLayout.setLayoutParams(layoutParamsRoot);
LinearLayout.LayoutParams layoutParams;
//START set xPos
m_XPosLabel = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_XPosLabel.setLayoutParams(layoutParams);
m_XPosLabel.setText(R.string.xPosLabel);
m_XPosValue = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_XPosValue.setLayoutParams(layoutParams);
m_XPosValue.setText(R.string.emptyString);
LinearLayout xlabelsLayout = new LinearLayout(this);
xlabelsLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
xlabelsLayout.setLayoutParams(layoutParams);
xlabelsLayout.addView(m_XPosLabel);
xlabelsLayout.addView(m_XPosValue);
//END set xPos
//START set yPos
m_YPosLabel = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_YPosLabel.setLayoutParams(layoutParams);
m_YPosLabel.setText(R.string.yPosLabel);
m_YPosValue = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_YPosValue.setLayoutParams(layoutParams);
m_YPosValue.setText(R.string.emptyString);
LinearLayout ylabelsLayout = new LinearLayout(this);
ylabelsLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
ylabelsLayout.setLayoutParams(layoutParams);
ylabelsLayout.addView(m_YPosLabel);
ylabelsLayout.addView(m_YPosValue);
//END set yPos
//START set zPos
m_ZPosLabel = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_ZPosLabel.setLayoutParams(layoutParams);
m_ZPosLabel.setText(R.string.zPosLabel);
m_ZPosValue = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_ZPosValue.setLayoutParams(layoutParams);
m_ZPosValue.setText(R.string.emptyString);
LinearLayout zlabelsLayout = new LinearLayout(this);
zlabelsLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
zlabelsLayout.setLayoutParams(layoutParams);
zlabelsLayout.addView(m_ZPosLabel);
zlabelsLayout.addView(m_ZPosValue);
//END set zPos
//START set marker name
m_MarkerNameLabel = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_MarkerNameLabel.setLayoutParams(layoutParams);
m_MarkerNameLabel.setText(R.string.markerNameLabel);
m_MarkerNameValue = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_MarkerNameValue.setLayoutParams(layoutParams);
m_MarkerNameValue.setText(R.string.emptyString);
LinearLayout markerNamelabelsLayout = new LinearLayout(this);
markerNamelabelsLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
markerNamelabelsLayout.setLayoutParams(layoutParams);
markerNamelabelsLayout.addView(m_MarkerNameLabel);
markerNamelabelsLayout.addView(m_MarkerNameValue);
//END set marker name
//START set score
m_ScorePosLabel = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_ScorePosLabel.setLayoutParams(layoutParams);
m_ScorePosLabel.setText(R.string.scoreLabel);
m_ScorePosValue = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_ScorePosValue.setLayoutParams(layoutParams);
m_ScorePosValue.setText(R.string.emptyString);
LinearLayout scorelabelsLayout = new LinearLayout(this);
scorelabelsLayout.setOrientation(LinearLayout.HORIZONTAL);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
scorelabelsLayout.setLayoutParams(layoutParams);
scorelabelsLayout.addView(m_ScorePosLabel);
scorelabelsLayout.addView(m_ScorePosValue);
//END set score
//END set msg
m_MessageTextView = new TextView(this);
layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(marginPixel, 0, 0, 0);
m_MessageTextView.setLayoutParams(layoutParams);
//END set msg
//Add to view
labelsLayout.addView(xlabelsLayout);
labelsLayout.addView(ylabelsLayout);
labelsLayout.addView(zlabelsLayout);
labelsLayout.addView(markerNamelabelsLayout);
labelsLayout.addView(scorelabelsLayout);
labelsLayout.addView(m_MessageTextView);
rootLayout.addView(labelsLayout);
}
#Override
public void uncaughtException(Thread t, Throwable ex) {
Log.e(TAG, "ViewWorldSample EXCEPTION:" + ex.getMessage());
finish();
}
}
The gradle file (I tried with 25.0.1 and 25.1.0 with no effect):
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "webdata.com.mascotcollector"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
testCompile 'junit:junit:4.12'
compile files('libs/AndAR.jar')
}
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 am using one one layout and include 5 times on other layout. but i want to user Grid View instance of incluide layout. Here I am sharing Screen shot. please help me to make this layout in android
This is Flipboard layout. and second one is my layout.
GridView does not support this. One has to use a custom linearlayout and add views to it dynamically by setting the layout parameters.
Use the class as layout back bone
public class CompositeView extends LinearLayout {
private ImageView imageView;
private TextView textView;
public CompositeView(Context context) {
super(context);
imageView = new ImageView(context);
imageView.setClickable(true);
imageView.setPadding(3, 3, 3, 3);
LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(params);
imageView.setScaleType(ScaleType.FIT_XY);
textView = new TextView(context);
textView.setTextColor(getResources().getColor(android.R.color.white));
textView.setClickable(true);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
textView.setSingleLine(true);
textView.setEllipsize(TruncateAt.END);
textView.setPadding(3, 3, 3, 3);
textView.setBackgroundResource(R.drawable.strip_bg);
this.setGravity(Gravity.CENTER);
// this.setClickable(true);
this.addView(imageView);
this.addView(textView);
}
public void setText(int resid) {
textView.setText(resid);
}
public void setText(CharSequence text) {
textView.setText(text);
}
public void setIcon(int resid) {
imageView.setImageDrawable(getResources().getDrawable(resid));
}
public ImageView getImageView() {
return imageView;
}
public TextView getTextView() {
return textView;
}
}
In activity or fragment
names = new String[] { "Cloud Bingo", "New Bingo Games", "Politricks",
"Seam Group", "Regular Cloud Bingo" };
urls = new String[] { "http://www.cloudbingo.co.uk/",
"http://www.newbingogames.co.uk/",
"http://www.politricks.co.in", "http://veenagupta.in/",
"http://www.regularbingo.co.uk/" };
for (int i = 0; i < images.length; i++) {
view = new CompositeView(getActivity());
view.setText(names[i]);
// view.setOnClickListener(this);
view.setOrientation(LinearLayout.VERTICAL);
view.setIcon(images[i]);
view.setId(i); // id of whole linear view
view.getTextView().setGravity(Gravity.CENTER);
view.getImageView().setId(i); // id of just this imageview
view.getTextView().setId(i);
}
Use following logic for your purpose
for (int i = 0; i < images.length; i++) {
flag++;
if (flag % 2 == 0) {
// number is even
mainLayout.addView(compositeList.get(i));
}
else {
Log.v("in", "else");
secondaryLayout = new LinearLayout(getActivity());
LayoutParams params = new LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 15, 0, 15);
secondaryLayout.setLayoutParams(params);
secondaryLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout leftLayout = new LinearLayout(getActivity());
leftLayout.setLayoutParams(new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
leftLayout.addView(compositeList.get(i));
secondaryLayout.addView(leftLayout);
i++;
if (i < images.length) {
LinearLayout rightLayout = new LinearLayout(getActivity());
LayoutParams rParams = new LayoutParams(0,
LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
rParams.setMargins(10, 0, 0, 0);
rightLayout.setLayoutParams(rParams);
rightLayout.addView(compositeList.get(i));
secondaryLayout.addView(rightLayout);
}
else {
LinearLayout rightLayout = new LinearLayout(getActivity());
LayoutParams rParams = new LayoutParams(0,
LinearLayout.LayoutParams.MATCH_PARENT, 1.0f);
rParams.setMargins(10, 0, 0, 0);
rightLayout.setLayoutParams(rParams);
secondaryLayout.addView(rightLayout);
}
mainLayout.addView(secondaryLayout);
}
}
flag is equal to -1 initially , I show one image (with text at bottom) for even rows, two images for odd rows
Here is the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="5"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<LinearLayout
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
I am working on an Android App. I have some problem..
Here is my app :
The pink rectangle is a ScrollView. I want to add TextView to the same ScrollView. I know I need a LinearLayout and add my Views inside this layout. After I need to add the LinearLayout to my ScrollView. Here is my ScrollView class with my methods setClassicLabel to implement TextViewand setClassicButton to implement Button in my ScrollView.
Here is my ScrollView.java :
public class MyScrollView extends ScrollView {
private JSONParser jParser;
private JSONObject contenuScrollView;
private Context context;
#SuppressLint("NewApi")
public MyScrollView(Context context, JSONArray listScrollView) throws JSONException {
super(context);
this.context = context;
}
public void onCreate(Bundle savedInstanceState) throws JSONException {
}
/* Création de TextView */
public void setClassicLabel(JSONArray listLabel, LinearLayout ll) throws JSONException {
if (listLabel.length() > 0)
{
DisplayMetrics metrics = new DisplayMetrics();
ll = new LinearLayout(getContext());
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams paramsll = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < listLabel.length(); i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (getContext().getResources().getDisplayMetrics().widthPixels * listLabel.getJSONObject(i).getDouble("size_x")),
(int) (getContext().getResources().getDisplayMetrics().heightPixels * listLabel.getJSONObject(i).getDouble("size_y")));
params.leftMargin = (int) (getContext().getResources().getDisplayMetrics().widthPixels * listLabel.getJSONObject(i).getDouble("position_x"));
params.topMargin = (int) (getContext().getResources().getDisplayMetrics().heightPixels * listLabel.getJSONObject(i).getDouble("position_y"));
TextView tv = new TextView(context);
tv.setText(listLabel.getJSONObject(i).getString("text"));
tv.setTextSize(listLabel.getJSONObject(i).getInt("police_size"));
tv.setTextColor(Color.parseColor(listLabel.getJSONObject(i).getString("colortext")));
tv.setBackgroundColor(Color.parseColor(listLabel.getJSONObject(i).getString("color")));
ll.addView(tv, params);
}
this.addView(ll, paramsll);
}
}
#SuppressWarnings("deprecation")
public void setClassicButton(JSONArray listButton, LinearLayout ll) throws JSONException {
if (listButton.length() > 0)
{
DisplayMetrics metrics = new DisplayMetrics();
ll = new LinearLayout(getContext());
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams paramsll = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < listButton.length(); i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (getContext().getResources().getDisplayMetrics().widthPixels * listButton.getJSONObject(i).getDouble("size_x")),
(int) (getContext().getResources().getDisplayMetrics().heightPixels * listButton.getJSONObject(i).getDouble("size_y")));
params.leftMargin = (int) (getContext().getResources().getDisplayMetrics().widthPixels * listButton.getJSONObject(i).getDouble("position_x"));
params.topMargin = (int) (getContext().getResources().getDisplayMetrics().heightPixels * listButton.getJSONObject(i).getDouble("position_y"));
int dest = listButton.getJSONObject(i).getInt("dest");
MyButton myButton = new MyButton(context, dest);
RoundRectShape rect = new RoundRectShape(
new float[] {50,50, 50,50, 50,50, 50,50},
null,
null);
ShapeDrawable bg = new ShapeDrawable(rect);
bg.getPaint().setColor(Color.parseColor(listButton.getJSONObject(i).getString("color")));
myButton.setBackgroundDrawable(bg);
myButton.setTextColor(Color.parseColor(listButton.getJSONObject(i).getString("colortext")));
//BitmapDrawable bdra = new BitmapDrawable(downloadBitmap(listButton.getJSONObject(i).getString("http")));
myButton.setText(listButton.getJSONObject(i).getString("text"));
myButton.getBackground().setAlpha(30);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
MyButton button = (MyButton)view;
Intent intent = new Intent(context, ClassicView.class);
Content content = new Content(button.getDestination());
intent.putExtra("CONTENT", content);
context.startActivity(intent);
}
});
ll.addView(myButton, params);
}
this.addView(ll, paramsll);
}
}
}
MyScrollView heritates from ScrollView. The problem is the next :
When I create my ScrollView with the method setClassicScrollView, i call my methods setClassicLabel and setClassicButton to implements theses two views in my ScrollView. But i can only set Button or Label. I can't set one label and one button. I must have a problem who comes from a layout.. I am on it for two days
Here is my method setClassicScrollView :
public void setClassicScrollView(JSONArray listScrollView, RelativeLayout rl) throws JSONException {
if (listScrollView.length() > 0) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
for (int i = 0; i < listScrollView.length(); i++) {
MyScrollView myScrollView = new MyScrollView(this, listScrollView);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams paramsll = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) (metrics.widthPixels * listScrollView.getJSONObject(i).getDouble("size_x")), (int) (metrics.heightPixels * listScrollView.getJSONObject(i).getDouble("size_y")));
params.leftMargin = (int) (metrics.widthPixels * listScrollView.getJSONObject(i).getDouble("position_x"));
params.topMargin = (int) (metrics.heightPixels * listScrollView.getJSONObject(i).getDouble("position_y"));
myScrollView.setBackgroundColor(Color.RED);
myScrollView.setLayoutParams(params);
myScrollView.setHorizontalScrollBarEnabled(true);
myScrollView.getMaxScrollAmount();
myScrollView.getBackground().setAlpha(50);
//myScrollView.setClassicLabel(listScrollView.getJSONObject(i).getJSONArray("Label"), ll);
myScrollView.setClassicButton(listScrollView.getJSONObject(i).getJSONArray("Button"), ll);
rl.addView(myScrollView);
}
}
}
Someone has an idea of how I can set TextViews and Buttons in the same ScrollView ?
Here's the layout for your scroll view.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Spinner
android:id="#+id/spending_report_cycle_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:id="#+id/SomeView2"
android:layout_width="wrap_content"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:background="#008080"
android:orientation="vertical" />
<fragment
android:id="#+id/fragment_content_1"
android:name="com.mike.passintents.Fragment1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:id="#+id/SomeView2"
android:layout_width="wrap_content"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:background="#008080"
android:orientation="vertical" />
<ListView
android:id="#+id/spending_report_listview"
android:layout_width="fill_parent"
android:layout_height="300dp"
android:background="#333333" >
</ListView>
</LinearLayout>
</ScrollView>
Here.. In the scroll view, I have one linear layout as one child and after that I have other views inside the linear layout.