Custom EditText settext does not set the text - android

I am using a custom edittext but the problem is that I am unable to set a text for my custom edittext. Here is what all I tried from the available answers on SO,
setText not working for a Custom Edittext
This did not work still. I did not get any error,so no clued why it did not work.
Custom TextView - setText() called before constructor
This also did not work.
XML FILE
<LinearLayout 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"
android:layout_gravity="center"
android:background="#FFFFFF"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<com.random.practiceproject.LinedEditText
android:layout_width="301dp"
android:inputType="text"
android:layout_height="match_parent" />
</LinearLayout>
MainActivity
LinedEditText lt;
EditText et; //Normal edittext works
String s = "This is a sample string";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lt = new LinedEditText(this);
et = (EditText) findViewById(R.id.newt);
lt.setCursorVisible(true);
lt.setTextColor(Color.BLACK);
lt.setText(s,TextView.BufferType.EDITABLE);
et.setText(s, TextView.BufferType.EDITABLE);
}
Here is the code,
public class LinedEditText extends EditText {
private static Paint linePaint;
static {
linePaint = new Paint();
linePaint.setColor(Color.BLACK);
linePaint.setStyle(Paint.Style.STROKE);
}
public LinedEditText(Context context)
{
super(context);
}
public LinedEditText(Context context, AttributeSet attributes) {
super(context, attributes);
}
#Override
protected void onDraw(Canvas canvas) {
Rect bounds = new Rect();
int firstLineY = getLineBounds(0, bounds);
/*int firstLineY=0;
for(int i =0;i<getLineCount();i++)
{
firstLineY = (i + 1) * getLineHeight();
}*/
int lineHeight = getLineHeight();
int totalLines = Math.max(getLineCount(), getHeight() / lineHeight);
for (int i = 0; i < totalLines; i++) {
int lineY = firstLineY + i * lineHeight;
canvas.drawLine(bounds.left, lineY, bounds.right, lineY, linePaint);
}
super.onDraw(canvas);
}
}

The problem is that you create new instance of LineEditText in onCreate and working with it, but not adding to layout. In the layout there is another instance of LineEditText, that you don't use.
So you must either replace:
lt = new LinedEditText(this);
with:
lt = (LinedEditText) findViewById(/*provide your id*/)
or you need to add lt to layout through ViewGroup.addView(), but I think you need to use first variant.

Related

Custom View onDraw() is being called but not appearing

SOLVED: I fixed the problem, it had to do with the constraints in my layout.
I am trying to create a custom view that for the time being simply displays a chart. This is my custom View class:
public class ChartView extends View {
private final Paint paint;
public ChartView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setWillNotDraw(false);
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
}
#Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("View ", "onDraw called");
int x = getWidth();
int y = getHeight();
int divX = x / 5;
int divY = y / 7;
for (int i = 0; i <= 5; i++) {
canvas.drawLine(divX * i, 0, divX * i, y, paint);
Log.d("View", "line drawn");
}
for (int i = 0; i <= 7; i++) {
canvas.drawLine(0, divY * i, x, divY * i, paint);
Log.d("View", "line drawn");
}
}
}
At first I assumed onDraw() must not ever have been called, but I added the log messages and it was in fact being called and each line in the chart was being drawn. I also have overridden onMeausure() so I don't think thats the problem.
Just to test if anything would be drawn at all I added in a test TextView which appeared just fine. I Then found that my chartView instance in the Main activity was null because I didn't call the parent constructor properly. I fixed that though and still nothing was drawn. However, when I fixed the problem with the parent constructor, the TextView also disappeared.
This is my Main Activity:
public class MainActivity extends AppCompatActivity {
private ChartView chartView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent mainIntent = getIntent();
boolean testPassed = mainIntent.getBooleanExtra("test", false);
if (testPassed) {
Log.d("Main", "intents test passed");
}
chartView = (ChartView) findViewById(R.id.chartView);
}
and this is my layout XML file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:visibility="visible"
tools:context=".MainActivity">
<Views.ChartView
android:id="#+id/chartView"
android:layout_width="425dp"
android:layout_height="634dp"
android:layout_marginEnd="601dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/textView"
android:layout_width="260dp"
android:layout_height="292dp"
android:layout_marginTop="256dp"
android:text="TextView"
android:textSize="100dp"
app:layout_constraintBottom_toTopOf="#+id/chartView"
app:layout_constraintEnd_toStartOf="#+id/chartView"
app:layout_constraintHorizontal_bias="0.582"
app:layout_constraintStart_toEndOf="#+id/chartView"
app:layout_constraintTop_toBottomOf="#+id/chartView"
app:layout_constraintVertical_bias="0.801" />
</androidx.constraintlayout.widget.ConstraintLayout>
Any help would be appreciated.

How to have text views that move along the progress bar

Context: I want to build a horizontal progress bar with some values and want to put some text that move along below this progress bar. So my final ideia is something like this (I already have the progress bar built I only left the text views below)
My current code is something like this:
This is my StackedHorizontalProgressBar class:
public class StackedHorizontalProgressBar extends ProgressBar {
private Paint paint;
int primary_progress, max_value;
public StackedHorizontalProgressBar(Context context) {
super(context);
init();
}
public StackedHorizontalProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
#Override public synchronized void setMax(int max) {
this.max_value = max;
super.setMax(max);
}
#Override public synchronized void setProgress(int progress) {
if (progress > max_value) {
progress = max_value;
}
this.primary_progress = progress;
super.setProgress(progress);
}
#Override public synchronized void setSecondaryProgress(int secondaryProgress) {
if ((primary_progress + secondaryProgress) > max_value) {
secondaryProgress = (max_value - primary_progress);
}
super.setSecondaryProgress(primary_progress + secondaryProgress);
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLACK);
primary_progress = 0;
max_value = 100;
}
}
This is my Main Activity layout (that uses above class)
<android.support.constraint.ConstraintLayout
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: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">
<github.nisrulz.stackedhorizontalprogressbar.StackedHorizontalProgressBar
android:id="#+id/stackedhorizontalprogressbar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:progressDrawable="#drawable/stacked_horizontal_progress"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="16dp" />
</android.support.constraint.ConstraintLayout>
This is my MainActivity class:
public class MainActivity extends AppCompatActivity {
int max = 100;
int countPrimary = 20;
int countSecondary = 30;
StackedHorizontalProgressBar stackedHorizontalProgressBar;
TextView txt_primary, txt_secondary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stackedHorizontalProgressBar =
(StackedHorizontalProgressBar) findViewById(R.id.stackedhorizontalprogressbar);
stackedHorizontalProgressBar.setMax(max);
stackedHorizontalProgressBar.setProgress(countPrimary);
txt_primary.setText("Primary Value : " + countPrimary + "%");
stackedHorizontalProgressBar.setSecondaryProgress(countSecondary);
txt_secondary.setText("Secondary Value : " + countSecondary + "%");
}
}
I think I must use canvas for this, so if there is anyone with experience with this that can help me.
public class ProgressBarAvtivity extends AppCompatActivity {
ProgressBar progressBar;
TextView tvProgress;
int d = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar_avtivity);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setProgress(d);
tvProgress = (TextView)findViewById(R.id.tvProgress);
tvProgress.setText(String.valueOf(d));
if (d > 40) {
tvProgress.setX(((width )* d / 100) - (d/2));
}
else {
tvProgress.setX(((width )* d / 100));
}
}}

Adding graphics views android layout

This will be my first question, so I apologize for my probable mistakes.
I'm trying to add a red circle each time I press the button I've incorported to my layout. I'd like all circles stayed in the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/panelJuego"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.76"
android:orientation="horizontal" >
</LinearLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="botonRojo"
android:text="Button" />
</LinearLayout>
The java code related with my trying is:
public void botonRojo(View v) {
LinearLayout panelJuego = (LinearLayout) findViewById(R.id.panelJuego);
PonCirculo circulo = new PonCirculo(this, 30, 30, "#FF0000");
circulo.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
panelJuego.addView(circulo);
}
public class PonCirculo extends View {
private int radio = 30;
private String color;
public PonCirculo(Context context, int x, int y, String color) {
super(context);
Cx = Cx + x;
Cy = Cy + y;
this.color = color;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(Cx, Cy, radio, paint);
}
Actually each time I press the button a red filled circle appears in the android screen but when I press the button again a new circle appears and the fomer disappears. Can anyone help me? Thanks.
I'm assuming you are just trying to add each circle under each other when the button is pressed.
Currently you are adding a new view each time now but it is over-laying the previous view. You need add the views giving each new circle a unique id. Then place the new circle underneath or whatever position you choose. I'm giving you some example code that I changed to use a relative layout and I place each circle under the previous one. This should get you started with what you are looking for:
Example Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relativeCircleLayout">
</RelativeLayout>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Circle"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:onClick="botonRojo"/>
</RelativeLayout>
Example Code:
public class MainActivity extends AppCompatActivity {
ArrayList<PonCirculo> viewList = new ArrayList<PonCirculo>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void botonRojo(View v) {
RelativeLayout panelJuego = (RelativeLayout) findViewById(R.id.relativeCircleLayout);
PonCirculo circulo = new PonCirculo(this, 30, 30, "#FF0000");
circulo.setId(View.generateViewId());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
if(!viewList.isEmpty()) {
int id = viewList.get(viewList.size()-1).getId();
params.addRule(RelativeLayout.BELOW, id);
}
panelJuego.addView(circulo, params);
viewList.add(circulo);
}
public class PonCirculo extends View {
private int radio = 30;
private String color;
int Cx, Cy;
public PonCirculo(Context context, int x, int y, String color) {
super(context);
Cx = Cx + x;
Cy = Cy + y;
this.color = color;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(Cx, Cy, radio, paint);
}
}
}

Android: Adding text to a View

I'm trying to add a text element to a view that's been created. I've found some answers online, but haven't been able to tailor them. I'm using the TouchPaint example code. Every-time I run the app with the text element, the app fails. Would appreciate some help.
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and attach the view that is responsible for painting.
mView = new MyView(this);
setContentView(mView);
mView.requestFocus();
TextView tvX= (TextView)findViewById(R.id.pointSize);
tvX.setText("TestText");
// Restore the fading option if we are being thawed from a
// previously saved state. Note that we are not currently remembering
// the contents of the bitmap.
mFading = savedInstanceState != null ? savedInstanceState.getBoolean("fading", true) : true;
}
View class
public class MyView extends View {
private static final int FADE_ALPHA = 0x06;
private static final int MAX_FADE_STEPS = 256/FADE_ALPHA + 4;
private Bitmap mBitmap;k
private Canvas mCanvas;
private final Rect mRect = new Rect();
private final Paint mPaint;
private final Paint mFadePaint;
private boolean mCurDown;
private int mCurX;
private int mCurY;
private float mCurPressure;
private float mCurSize;
private int mCurWidth;
private int mFadeSteps = MAX_FADE_STEPS;
public MyView(Context c) {
super(c);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setARGB(255, 255, 255, 255);
mFadePaint = new Paint();
mFadePaint.setDither(true);
mFadePaint.setARGB(FADE_ALPHA, 0, 0, 0);
}
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="${packageName}.${activityClass}" >
<TextView
android:id="#+id/pointSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textColor="#FF0000"
android:visibility="visible" />
</RelativeLayout>
Try this:
LinearLayout lv = new LinearLayout(this);
tvX.setText("TestText");
lv .addView(tvX);
setContentView(lv);

Adding view onto an activity

If I want to add a button in this class so that I can call the onclicklistener, how should I do it?
public class GameView extends View {
Path circle;
Paint cPaint;
Paint tPaint;
String z;
int i = 65, strt, arc, leftx, topy, rightx, bottomy, maxx, maxy;
boolean flag1, flag2, flag3;
double n1, n2;
int n, n3 = 180,n4,n5 = 90;
float f1 = 180, f2 = 90;
Button b1;
Random r = new Random();
RectF oval;
public GameView(Context context) {
super(context);
leftx = 0;
topy = 60;
rightx = 150;
bottomy = 120;
z = String.valueOf(Character.toChars(i));
cPaint = new Paint();
cPaint.setColor(Color.RED);
strt = 45;
arc = 315;
n1 = Math.random() * 600;
Log.d("random", z);
if (flag2 == false)
new DrawThread(this);
// cPaint.setStrokeWidth(2);
tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tPaint.setColor(Color.BLACK);
float scale = getResources().getDisplayMetrics().scaledDensity;
tPaint.setTextSize(20 * scale);
}
public void onSizeChanged(int w,int h,int oldh,int oldw) {
maxx = oldw;
maxy = oldh;
}
//#Override
protected void onDraw(Canvas canvas) {
// Drawing commands go here
oval = new RectF(leftx,topy,rightx,bottomy);
canvas.drawArc(oval, strt, arc, true, cPaint);
while (i < 90) {
canvas.drawText(String.valueOf(Character.toChars(i)),f1,f2, tPaint);
break;
}
}
}
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
add the above below setContentView
setContentView(R.layout.activity_new_game);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
You need to set the layout using setContentView and then initialize views.
Note you can findViewById of the current view hierarchy set to the activity
Edit:
Example: This is an example. I don't see why it won't work if you do similar as below.
<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=".NewGame"
android:id="#+id/relative_layout"
>
<Button
android:id="#+id/prev_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/next_button"
android:layout_alignBottom="#+id/next_button"
android:layout_centerHorizontal="true"
android:text="stop_label" />
<Button
android:id="#+id/next_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="20dp"
android:layout_toLeftOf="#+id/prev_button"
android:text="start_label" />
<RelativeLayout
android:layout_width="wrap_content"
android:id="#+id/rl"
android:layout_below="#+id/prev_button"
android:layout_height="wrap_content"
>
</RelativeLayout>
</RelativeLayout>
Activity
public class MainActivity extends Activity {
private Button btn1;
private EditText edt1, edt2, edt3, edt4 ,edt5, edt6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyView mv = new MyView(this);
setContentView(R.layout.activity_main);
RelativeLayout layout= (RelativeLayout) findViewById(R.id.rl);
layout.addView(mv);
}
class MyView extends View
{
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.RED);
}
}
}
snapshot
You need to inflate your view before trying to find your relative layout. Try :
RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gameview=new GameView(this);
setContentView(R.layout.activity_new_game);
layout = (RelativeLayout) findViewById(R.id.relative_layout);
//LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//view = mInflater.inflate(R.layout.activity_new_game, gameview, true);
layout.addView(gameview);
}
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
you can't call findViewById before setContentView. Move
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
after setContentView(R.layout.activity_new_game);
you didn't initialize layout in your code so First initialize layout after setContentView then add view to your layout
RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_game);
//Initialize game view
GameView gameview=new GameView(this);
//initialize layout
layout = (RelativeLayout) findViewById(R.id.relative_layout);
//adding game view to layout
layout.addView(gameview);
}
Edit:
initializing like this before setContentView
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relative_layout);
is wrong approach you must initialize views only after setContentView like the above code

Categories

Resources