How to add textviews to a horizontalScrollView programmatically ? - android

I am trying to programatically add a whole bunch of textViews of a certain width and at a certain location onto a tab. Now their setX() might be placed beyond the resolution of the screen. For instance, my tab is 1240 pixels in width, and I want to place a TextView at 2000 pixels and of course have a horizontal scroll feature available. I'm essentially creating a timeline on the fly depending on the data pulled.
I'm just trying to (at the moment) get multiple TextViews thrown on to the screen, and to have the horizontal scroll view for them. I am not sure if even doing a setX(2000); will populate a TextView beyond the screen. How can I get the HorizontalScrollView to work so that I may slide my main layout to the right to see the remaining two TextViews that were created?
Some basic code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="horizontal">
<HorizontalScrollView
android:id="#+id/horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</HorizontalScrollView>
</RelativeLayout>
The MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
for(int i = 50; i < 550; i+=100){
TextView myText = new TextView(this);
myText.setX(i * 3);
myText.setText("HELLLLLOOOO");
layout.addView(myText);
}
}
#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;
}
}

MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout sv = (LinearLayout)findViewById(R.id.ll);
for(int i = 50; i < 550; i+=50){
TextView myText = new TextView(this);
myText.setX(i * 3);
myText.setText("HELLLLLOOOO");
sv.addView(myText);
}
}
#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;
}
}
xml
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="#+id/ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>

Create one custom view for example
public class Example extends HorizontalScrollView {
}
Execute all unimplemented methods, then write this:
LinearLayout l = new LinearLayout(context);
TextView tv = new TextView(context);
tv.setText("Example");
tv.setTextColor(Color.RED);
l.addView(tv);
addView(l);
Now in your xml, put the packagename and class name like this:
<com.argha.Example android:height and all />
Done, now you have HorizontalScroll view with a TextView... more text you want just do same as above.
Sorry if you found any code error, because I typed with my phone.

Related

Switching visibility of text field when changing number of columns gridview

I'm current having a problem designing an activity which can switch from a 'grid' to 'list' view. I'm using a GridView and to switch to the 'list', I set the maximum number of columns to 1. Now my problem is that when I switch to 'list' view, I want the image on the left along with some text on the right and not just an image in the center. All the data is taken from a custom class which is populated manually. The following images will demonstrate.
What I want:
What I have:
My Code (XML and Java) is as follows:
single_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:contentDescription="#string/content"
android:id="#+id/imageView1"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gridview.MainActivity"
tools:ignore="MergeRootFrame" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="128dp"
android:verticalSpacing="10dp"
>
</GridView>
</FrameLayout>
MainActivity.java
private GridView myGrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myGrid = (GridView) findViewById(R.id.gridView1);
myGrid.setAdapter(new myGridAdapter(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
GridView gv = (GridView) findViewById(R.id.gridView1);
//ImageView iv = (ImageView) findViewById(R.id.imageView1);
switch (item.getItemId()) {
case R.id.action_grid:
Toast.makeText(this, "Grid Button", Toast.LENGTH_SHORT).show();
gv.setNumColumns(GridView.AUTO_FIT);
return true;
case R.id.action_list:
Toast.makeText(this, "List Button", Toast.LENGTH_SHORT).show();
gv.setNumColumns(1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Does anyone have any idea how I can accomplish this? I've been reading for quite some time now and have also thought of viewSwitcher and viewFlipper but don't think that they are exactly what I'm looking for. I've also juggled with the idea of creating separate activities for each layout but then also read about the drawbacks.
Thanks for your time.
The simplest option would probably be:
Add a TextView in single_item.xml, and position it to the right of the image.
Pass the current state of the GridView (i.e. the mode it's in) to your custom adapter.
In the Adapter's getView(), depending on this state:
Call setVisibility() on the TextView, with either VISIBLE or GONE.
Update the ImageView's layoutParams, to align it to the center or right of its parent.
This does not require any duplication.
Example code:
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = LayoutInflater.from(mContext)inflate(...);
}
TextView tv = convertView.findViewById(R.id.textView1);
ImageView imageView = convertView.findViewById(R.id.imageView1);
// Show/hide text according to ListView mode.
tv.setVisibility(mMode == SHOW_TEXT ? View.VISIBLE : View.GONE);
// also update imageView.getLayoutParams() according to mMode.

TextView failure

I'm programming my first android app.
I want to set text on a TextView.
(I already searched here and found out, how to do it...But it still don't work)
Do you know, what the problem is?
This is my Java code.
package com.example.randomcraps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import com.example.*;
public class MainActivity extends Activity {
TextView text = (TextView) findViewById(R.layout.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void getRandomNumber(){
int i;
double savePoint;
savePoint = Math.random();
savePoint = savePoint*100+1;
i = (int)savePoint;
text.setText(i);
}
}
This is my XML Code
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
android:text="#string/Button1"
android:onClick="getRandomNumber" />
<TextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/RandomNumber" />
</RelativeLayout>
Change to
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.number); // id of textview in activity_main.xml
}
findViewById looks for a view with the id mentioned in the current inflated layout. So you need to set layout to the activity and then initialize your views.
Also change
text.setText(i);
// looks for a resource with the id mentioned if not found you get ResourceNotFoundException
To
text.setText(String.valueOf(i));
// int i; i is an int value. Use String.valueOf(intvalue)
Edit:
Your method signature is different. It should be
public void getRandomNumber(View V){ // missing View as param
... //rest of the code
}
Coz you have
android:onClick="getRandomNumber"
Quoting from docs
public static final int onClick
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
Change your code to this.
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.number);
}
Also
text.setText(String.valueOf(i));
NOTE: findViewByID finds view from content. So basically you have to use that method after you set your content.
Set text color after setText and for guarantee set the font size. Sometimes it makes the color default white.

TextView does not appear when added dynamically

I am dynamically adding a TextView which does not appear, what seems to be the problem?
Is there a difference between following two lines:
receiptLayout.addView(order_1_confirm);
((LinearLayout) receiptLayout).addView(order_1_confirm);
Well, neither one of them does not work!
My activity_receipt.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/receiptMainLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageView
android:id="#+id/image_view_rsc_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/rsc_logo"
android:src="#drawable/rsc" />
and my ReceiptActivity.java:
public class ReceiptActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receipt);
LinearLayout receiptLayout = (LinearLayout)findViewById(R.id.receiptMainLinearLayout);
TextView order_1_confirm = new TextView(this);
order_1_confirm.setText("hello");
//receiptLayout.addView(order_1_confirm);
((LinearLayout) receiptLayout).addView(order_1_confirm);
}
#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;
}
}
Just give android:orientation="vertical" in your LinearLayout.
And in
LinearLayout receiptLayout = (`LinearLayout`)findViewById(R.id.receiptMainLinearLayout);
you are already casting view to LinearLayout so no need to cast it again
Set the size and color of the TextView. Perhaps it seems invisible because it is the same color as the background.
you should always add orientation to the LinearLayout, adding android:orientation="vertical" would works fine.

One button cover other button in linear layout in android

I'm having a problem with adding elements in code. I want to add two buttons to a horizontal linear layout. My code works, but the second button partially covers the first button.
Question: How can I make it so that the second button doesn't cover the first button?
This is the code:
public class MainActivity extends Activity {
Button buttonFirst, buttonSecond;
LinearLayout lau;
LayoutParams params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonFirst = new Button(getApplicationContext());
buttonSecond = new Button(getApplicationContext());
lau = (LinearLayout) findViewById(R.id.layoutmadafaka);
params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(-30, 0, 0, 0);
buttonSecond.setLayoutParams(lp);
buttonSecond.setBackgroundColor(Color.BLACK);
lau.addView(buttonFirst,params);
lau.addView(buttonSecond);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and 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=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<LinearLayout
android:id="#+id/layoutmadafaka"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
This must be done programmatically. When I use the bringToFront() method the buttons change positions but I don't want to do that. I want to first button on left side and second button next to first button.
I think its because of the negative margin you set :
lp.setMargins(-30, 0, 0, 0);
remove it or set them at 0 (its equivalent since 0 is the default value):
lp.setMargins(0, 0, 0, 0);
thoses negativbe margins displace the button2 to the left so its behind the other button.
You can't manage overlapping in LinearLayout (that's why a bringToFront action change order in the line and not overlapping order).
you need to use a RelativeLayout, set the button 2 to be on the right of button1, let the margin to -30 and call bringToFront on the second button it shoulc work ;)
You can set for your #id/layoutmadafaka the property android:weightSum=1.0 in xml.
And when you add the buttons, set for each layout_weight=0.5, layout_width=0.
Example here: Linear Layout and weight in Android

Null Pointer Exception Android onTouchListener onClickListener setText

New to programming android apps and keep getting a null pointer exception and im not sure why. Ive ressearched this a bit and it seems that most people get this because of the setContentView but it seems that from what everyone else is saying my setContentView is in the right space etc...
int randInt;
int[] randColor = {Color.RED,Color.BLUE,Color.GREEN,Color.YELLOW,Color.BLACK,
Color.CYAN,Color.MAGENTA,Color.LTGRAY,Color.DKGRAY,Color.WHITE};
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
View layout = findViewById(R.layout.activity_main);
layout.setOnTouchListener(this);
textView1 = (TextView) findViewById(R.id.textView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onClick(View v) {
setBackGroundColor(randInt);
}
#Override
public boolean onTouch(View v, MotionEvent e){
float xPos = e.getX();
float yPos = e.getY();
changeText(xPos,yPos);
return true;
}
public void setBackGroundColor(int randInt){
getWindow().setBackgroundDrawable(new ColorDrawable(randColor[getRandomInt()]));
}
public int getRandomInt(){
Random randomInt = new Random();
randInt = randomInt.nextInt(10);
return randInt;
}
public void changeText(float xPos, float yPos){
textView1.setText("You are at " + xPos + " , " + yPos);
}
}
<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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp"
android:text="#string/button" />
Assign an id to your layout:
<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=".MainActivity"
android:id="#+id/my_layout">
Then change your code as so:
View layout = findViewById(R.id.my_layout);
findViewByID(), like the method name says, needs an ID. Passing off a layout does pass an int, so it compiles fine, but it's unlikely you'll match against an id, and the method returns null.
If anything else also returns null, make sure your layout (and its children views) are contained in the xml file called activity_main.xml and that you have cleaned your project.
Instead of this statement
View layout = findViewById(R.layout.activity_main);
Change it to
View layout = findViewById(android.R.id.content);
findViewById(android.R.id.content) means You want to get the content view of an Activity
Replace your setContentView line with this:
LayoutInflater inflater = LayoutInflater.from(this);
View view = (View) inflater.inflate(R.layout.activity_main); // can't remember if casting is necessary here
setContentView(view);

Categories

Resources