Drag a Textfield to a new position - input

Im trying to get my TextField to move on the screen. I want to be able to drag it to a new position on the screen. I´ve been struggling with this for days now and I really cant figure this one out...
This is what I´ve done so far:
InputProcessor drag = new InputAdapter() {
#Override
public boolean touchDown(int screenX, int screenY, int pointer,
int button) {
// TODO Auto-generated method stub
return super.touchDown(screenX, screenY, pointer, button);
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer,
int button) {
int x = Gdx.input.getX();
int y = Gdx.input.getY();
textField.setPosition(x, y);
return true;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return super.touchDragged(screenX, screenY, pointer);
}
};
game.inputMultiplexer = new InputMultiplexer();
game.inputMultiplexer.addProcessor(stage);
game.inputMultiplexer.addProcessor(stagePurc);
game.inputMultiplexer.addProcessor(stageText);
game.inputMultiplexer.addProcessor(drag);
Gdx.input.setInputProcessor(game.inputMultiplexer);
Here´s the textfield:
final TextField textField = new TextField(prefs.getString("textField", "Enter name:"), textstyle);
textField.setX(textX);
textField.setY(textY);
textField.setMaxLength(20);
textField.setWidth(textWidth);
textField.setHeight(textHeight);

Put the TextView in a LinearLayout:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top|center_horizontal"
android:clipChildren="false"
android:gravity="center_horizontal|center_vertical"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/text_color"
android:textSize="16sp" />
</LinearLayout>
Then set a touch listener:
txt.setOnTouchListener(new View.OnTouchListener() {
int initialX = 0;
int initialY = 0;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
initialX = (int) event.getX();
initialY = (int) event.getY();
break;
case MotionEvent.ACTION_MOVE:
int currentX = (int) event.getX();
int currentY = (int) event.getY();
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) txt.getLayoutParams();
int left = lp.leftMargin + (currentX - initialX);
int top = lp.topMargin + (currentY - initialY);
int right = lp.rightMargin - (currentX - initialX);
int bottom = lp.bottomMargin - (currentY - initialY);
lp.rightMargin = right;
lp.leftMargin = left;
lp.bottomMargin = bottom;
lp.topMargin = top;
txt.setLayoutParams(lp);
break;
default:
break;
}
return true;
}
});
Works pretty well. I got this code from here: How to make the TextView drag in LinearLayout smooth, in android?

Related

Does detect faces need google play store?

i used the Detect faces with ML Kit on Android.i can get the result of detection, but the console printed the warning that
"W/GooglePlayServicesUtil: com.example.mlkitfacedemo requires the Google Play Store, but it is missing.
W/GoogleApiManager: The service for com.google.android.gms.common.internal.service.zap is not available: ConnectionResult{statusCode=SERVICE_INVALID, resolution=null, message=null}"
thanks for your help.
this is my whole code
// MainActivity2.java
public class MainActivity2 extends AppCompatActivity {
ImageView beforeIV, afterIV;
int imageMaxWidth;
int imageMaxHeight;
Bitmap resizedBitmap;
TextView tv;
private static final int[] COLORS = {
Color.TRANSPARENT,
Color.BLUE,
Color.RED,
Color.YELLOW,
Color.GREEN,
Color.MAGENTA,
Color.BLUE,
Color.RED,
Color.RED,
Color.BLUE,
Color.GRAY,
Color.LTGRAY,
Color.YELLOW,
Color.BLUE,
Color.CYAN,
Color.GREEN
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
beforeIV = findViewById(R.id.before);
// beforeIV.setImageResource(R.drawable.grapefruit);
afterIV = findViewById(R.id.after);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.grapefruit);
tv = findViewById(R.id.textView);
View rootView = findViewById(R.id.root);
rootView.getViewTreeObserver()
.addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
imageMaxWidth = rootView.getWidth();
imageMaxHeight = rootView.getHeight() / 2;
System.out.println("rootView Size: " + rootView.getWidth() + ", " + rootView.getHeight());
float scaleFactor =
max(
(float) bitmap.getWidth() / (float) imageMaxWidth,
(float) bitmap.getHeight() / (float) imageMaxHeight);
resizedBitmap =
Bitmap.createScaledBitmap(
bitmap,
(int) (bitmap.getWidth() / scaleFactor),
(int) (bitmap.getHeight() / scaleFactor),
true);
beforeIV.setImageBitmap(resizedBitmap);
detect();
}
});
}
private void detect() {
// 准备检测器
// High-accuracy landmark detection and face classification
FaceDetectorOptions highAccuracyOpts =
new FaceDetectorOptions.Builder()
.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
.setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
.build();
// Real-time contour detection
FaceDetectorOptions realTimeOpts =
new FaceDetectorOptions.Builder()
.setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)
.build();
InputImage image = InputImage.fromBitmap(resizedBitmap, 0);
FaceDetector detector = FaceDetection.getClient(highAccuracyOpts);
// Or use the default options:
// FaceDetector detector = FaceDetection.getClient();
Task<List<Face>> result =
detector.process(image)
.addOnSuccessListener(
new OnSuccessListener<List<Face>>() {
#Override
public void onSuccess(List<Face> faces) {
// Task completed successfully
// ...
System.out.println("检测成功");
Face face = faces.get(0);
List<FaceLandmark> allLandmarks = face.getAllLandmarks();
for (int i = 0; i < allLandmarks.size(); i++) {
System.out.println(allLandmarks.get(i).getPosition().x);
System.out.println(allLandmarks.get(i).getPosition().y);
}
Rect bounds = face.getBoundingBox();
Paint boxPaint = new Paint();
boxPaint.setStyle(Paint.Style.STROKE);
boxPaint.setColor(Color.RED);
boxPaint.setStrokeWidth(5.f);
Canvas canvas = new Canvas(resizedBitmap);
canvas.drawRect(bounds, boxPaint);
// getAllContours - 面部133个点
Paint pathPaint = new Paint();
pathPaint.setStrokeWidth(5.f);
pathPaint.setStyle(Paint.Style.STROKE);
List<FaceContour> allContours = face.getAllContours();
System.out.println("allContours size: " + allContours.size());
int sum = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < allContours.size(); i++) {
String string = "allContours[" + i + "]: " + allContours.get(i).getPoints().size();
System.out.println("allContours[" + i + "]: " + allContours.get(i).getPoints().size());
sum += allContours.get(i).getPoints().size();
builder.append(string);
pathPaint.setColor(COLORS[i]);
List<PointF> points = allContours.get(i).getPoints();
float bx = points.get(0).x;
float by = points.get(0).y;
for (int j = 0; j < points.size(); j++) {
float cx = points.get(j).x;
float cy = points.get(j).y;
String str = "points[" + j + "]: (" + cx + ", " + cy + "), ";
builder.append(str);
canvas.drawLine(bx, by, cx, cy, pathPaint);
bx = cx;
by = cy;
}
builder.append("\n");
}
System.out.println("sum: " + sum);
tv.setText(builder.toString());
runOnUiThread(() -> {
afterIV.setImageBitmap(resizedBitmap);
});
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
System.out.println("检测失败");
e.printStackTrace();
}
});
}
}
// activity_main2.xml
<?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:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
tools:context=".MainActivity2">
<ImageView
android:id="#+id/before"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"/>
<ImageView
android:id="#+id/after"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="#id/before"
app:layout_constraintLeft_toLeftOf="#id/before"
app:layout_constraintLeft_toRightOf="#id/before"
app:layout_constraintBottom_toBottomOf="#id/before"/>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/before"
app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
// in build.gradle
dependencies {
...
// google mlkit face detection
implementation 'com.google.mlkit:face-detection:16.1.5'
...
}

if statement doesn't check the values of the edittexts reached by scrolling the recyclerview

i have a recyclerview the has an edittext in each row. the user can change the value of the edittext as he wishes but it should not be left empty for the values will be saved in a database. for this i'm trying to check if the edittext is empty. if any row has an empty edittext, the user is given a message when he wants to save that there is an empty value. this is the code that i wrote:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_request_items context;
int selected_pos = -1;
private SwipeToDeleteCallback swipeToDeleteCallback;
List<list_item> item_details = new List<list_item>();
public recyclerviewAdapter(new_request_items context, DataTable sum_req, List<list_item> item_details)
{
this.context = context;
summary_Requests = sum_req;
this.item_details = item_details;
}
public recyclerviewAdapter(DataTable sum_req, SwipeToDeleteCallback swipeToDeleteCallback)
{
this.swipeToDeleteCallback = swipeToDeleteCallback;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_request_new_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
string itemcode = summary_Requests.Rows[position]["itemcode"].ToString();
list_item result = item_details.Find(list_item => list_item.item_code == itemcode);
Bundle bundle = new Bundle();
bundle.PutString("result", JsonConvert.SerializeObject(result));
items_info iteminf = new items_info();
iteminf.Arguments = bundle;
iteminf.Cancelable = true;
var SupportFragmentManager = this.context.FragmentManager;
iteminf.Show(SupportFragmentManager, "dialog");
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text= summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public void RemoveItem(int position)
{
if (laborers_dt_total.Rows.Count != 0)
{
if (position < laborers_dt_total.Rows.Count && position > -1)
{
laborers_dt_total.Rows.RemoveAt(position);
}
else
{
Toast.MakeText(context.Context, "select an item to delete", ToastLength.Long).Show();
}
}
else if (laborers_dt_total.Rows.Count == 0)
{
Toast.MakeText(context.Context, "no items to delete", ToastLength.Long).Show();
}
for (int i = 0; i < laborers_dt_total.Rows.Count; i++)
{
laborers_dt_total.Rows[i]["rowNumber"] = (i + 1).ToString();
NotifyDataSetChanged();
}
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
now it works well when there are only few rows in the recyclerview, but when there are many in which i have to scroll through it, if i keep an edittext empty in a row reached by scrolling, the user.zero_val doesn't take the value of exits to tell me that an edittext is empty. what should i do in this case? where do i check for empty edittext? thanks in advance.
this is a simple code i wrote with hopes it would illustrate my problem:
this is the axml of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="255sp"
android:id="#+id/recyclerView1" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" />
</LinearLayout>
this is the layout of each row of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/light_grey"
android:padding="1dp"
android:layout_marginTop="0.5dp"
android:weightSum="8"
android:gravity="center"
android:id="#+id/linearLayout"
>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:id="#+id/rownbr"
android:background="#drawable/back"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="4"
android:id="#+id/laborname"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
android:background="#drawable/back"
android:layout_marginLeft="2dp"/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/days"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
<EditText
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/overtime"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
</LinearLayout>
this is the back.xml drawable:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
this is the activity where the recyclerview is populated and managed:
public class MainActivity : AppCompatActivity
{
RecyclerView mRecyclerView;
DataTable dt = new DataTable();
RecyclerView.LayoutManager mLayoutManager;
recyclerviewAdapter RecyclerviewAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
dt.Columns.Add("rowNumber");
dt.Columns.Add("name");
dt.Columns.Add("itemsunitcode");
dt.Columns.Add("itemQty");
dt.Rows.Add("1", "rana hd", "pcs", "1");
dt.Rows.Add("2", "rana hd1", "pcs", "1");
dt.Rows.Add("3", "rana hd2", "pcs", "1");
dt.Rows.Add("4", "rana hd3", "pcs", "1");
dt.Rows.Add("5", "rana hd4", "pcs", "1");
dt.Rows.Add("6", "rana hd5", "pcs", "1");
dt.Rows.Add("7", "rana hd6", "pcs", "1");
dt.Rows.Add("8", "rana hd7", "pcs", "1");
dt.Rows.Add("9", "rana hd8", "pcs", "1");
dt.Rows.Add("10", "rana hd9", "pcs", "1");
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView1);
Button btn= FindViewById<Button>(Resource.Id.button1);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.HasFixedSize = true;
mRecyclerView.SetLayoutManager(mLayoutManager);
RecyclerviewAdapter = new recyclerviewAdapter(this, dt);
mRecyclerView.SetAdapter(RecyclerviewAdapter);
btn.Click += delegate
{
if (user.zero_val == "exits")
Toast.MakeText(this, "exists", ToastLength.Long).Show();
if (user.zero_val == "Not_exist")
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
}
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly MainActivity context;
int selected_pos = -1;
public recyclerviewAdapter(MainActivity context, DataTable sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recyclerview_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
selected_pos = position;
NotifyDataSetChanged();
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text = summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
}
}
this is the user class:
public static class user
{
public static string zero_val = "";
}
If I undstand your meanings correctly, I don't think it's correct to use variable zero_val in class user to indicate whether or not null values exist.For example ,if you have enter a empty value for the first EditText, then the value of zero_val will been changed to Not_exist, then if we enter another empty value for the second EditText, then the value of zero_val will also been changed to Not_exist,after that, if we change the second EditText to a correct value, then the value of zero_val will been changed to exits.But now, actually the first EditText still be empty.
I think you can verify the values the table DataTable when clicking button.
You can refer to the following code:
btn.Click += delegate
{
bool hasEmpty = false ;
foreach (DataRow row in dt.Rows)
{
string itemQty = row["itemQty"].ToString();
string rowNumber = row["rowNumber"].ToString();
System.Diagnostics.Debug.WriteLine("rowNumber =" + rowNumber + "< --- > itemQty = " + itemQty);
if (string.IsNullOrEmpty(itemQty)) {
hasEmpty = true;
}
}
//if (user.zero_val.Equals("exits"))
// Toast.MakeText(this, "exists", ToastLength.Long).Show();
//if (user.zero_val.Equals("Not_exist"))
// Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
if (!hasEmpty)
Toast.MakeText(this, "exists", ToastLength.Long).Show();
else
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
In addition, modify the TextChanged function in RecyclerviewAdapter:
vh.qty.TextChanged += (sender, e) =>
{
if (!vh.qty.Text.Equals(""))
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
//store a empty value for this textview
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = "";
}
else if (vh.qty.Text.Equals(""))
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
int position = vh.LayoutPosition;
//store a empty value for this textview
summary_Requests.Rows[position]["itemQty"] = "";
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
}
};

Text dissapears on QOpenGLWidget after undocking

I'm trying to integrate Qt5 and OpenSceneGraph. I've found this minimal example of embedding.
When I encapsulate the widget, defined in the example, into a QDockWidget and add a simple text label to the example, the text dissapears when I undock the container window. When I redock the window the text is shown no more.
I've already ask this on the OpenSceneGraph forum without success. My guess is that it has something to do with the GL related methods and the internal reparenting of the widgets.
In my example only the constructor and the main function are modified from the original.
This is my modified example (main.cpp):
#include<QApplication>
#include<QMainWindow>
#include<QOpenGLWidget>
#include<QMouseEvent>
#include<QWheelEvent>
#include<QDesktopWidget>
#include<QScreen>
#include<QtGlobal>
#include<QWindow>
#include<QWidget>
#include<QDockWidget>
#include<QVBoxLayout>
#include<osg/ref_ptr>
#include<osgViewer/GraphicsWindow>
#include<osgText/Text>
#include<osgViewer/Viewer>
#include<osg/Camera>
#include<osg/ShapeDrawable>
#include<osg/StateSet>
#include<osg/Material>
#include<osgGA/EventQueue>
#include<osgGA/TrackballManipulator>
#include <iostream>
#include <stdio.h>
class QtOSGWidget : public QOpenGLWidget
{
public:
QtOSGWidget(qreal scaleX, qreal scaleY, QWidget* parent = 0)
: QOpenGLWidget(parent)
, _mGraphicsWindow(new osgViewer::GraphicsWindowEmbedded( this->x(), this->y(),
this->width(), this->height() ) )
, _mViewer(new osgViewer::Viewer)
, m_scaleX(scaleX)
, m_scaleY(scaleY)
{
osg::Cylinder* cylinder = new osg::Cylinder( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f, 0.5f );
osg::ShapeDrawable* sd = new osg::ShapeDrawable( cylinder );
sd->setColor( osg::Vec4( 0.8f, 0.5f, 0.2f, 1.f ) );
osg::Geode* geode = new osg::Geode;
geode->addDrawable(sd);
// adding text to the visualization
osgText::Text * test = new osgText::Text();
test->setDataVariance(osg::Object::DYNAMIC);
test->setCharacterSize(1.0);
test->setColor(osg::Vec4(0.0, 0.0, 0.0, 1.0));
test->setAlignment(osgText::Text::CENTER_BOTTOM);
test->setAxisAlignment(osgText::TextBase::SCREEN);
test->setCharacterSizeMode(osgText::Text::OBJECT_COORDS);
test->setText("CYLINDER");
geode->addDrawable(test);
// end adding text
osg::Camera* camera = new osg::Camera;
camera->setViewport( 0, 0, this->width(), this->height() );
camera->setClearColor( osg::Vec4( 0.9f, 0.9f, 1.f, 1.f ) );
float aspectRatio = static_cast<float>( this->width()) / static_cast<float>( this->height() );
camera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
camera->setGraphicsContext( _mGraphicsWindow );
_mViewer->setCamera(camera);
_mViewer->setSceneData(geode);
osgGA::TrackballManipulator* manipulator = new osgGA::TrackballManipulator;
manipulator->setAllowThrow( false );
this->setMouseTracking(true);
_mViewer->setCameraManipulator(manipulator);
_mViewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
// _mViewer->realize();
}
virtual ~QtOSGWidget(){}
void setScale(qreal X, qreal Y)
{
m_scaleX = X;
m_scaleY = Y;
this->resizeGL(this->width(), this->height());
}
protected:
virtual void paintGL()
{
_mViewer->frame();
}
virtual void resizeGL( int width, int height )
{
this->getEventQueue()->windowResize(this->x()*m_scaleX, this->y() * m_scaleY, width*m_scaleX, height*m_scaleY);
_mGraphicsWindow->resized(this->x()*m_scaleX, this->y() * m_scaleY, width*m_scaleX, height*m_scaleY);
osg::Camera* camera = _mViewer->getCamera();
camera->setViewport(0, 0, this->width()*m_scaleX, this->height()* m_scaleY);
}
virtual void initializeGL()
{
osg::Geode* geode = dynamic_cast<osg::Geode*>(_mViewer->getSceneData());
osg::StateSet* stateSet = geode->getOrCreateStateSet();
osg::Material* material = new osg::Material;
material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE );
stateSet->setAttributeAndModes( material, osg::StateAttribute::ON );
stateSet->setMode( GL_DEPTH_TEST, osg::StateAttribute::ON );
}
virtual void mouseMoveEvent(QMouseEvent* event)
{
this->getEventQueue()->mouseMotion(event->x()*m_scaleX, event->y()*m_scaleY);
}
virtual void mousePressEvent(QMouseEvent* event)
{
unsigned int button = 0;
switch (event->button())
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonPress(event->x()*m_scaleX, event->y()*m_scaleY, button);
}
virtual void mouseReleaseEvent(QMouseEvent* event)
{
unsigned int button = 0;
switch (event->button())
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonRelease(event->x()*m_scaleX, event->y()*m_scaleY, button);
}
virtual void wheelEvent(QWheelEvent* event)
{
int delta = event->delta();
osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ?
osgGA::GUIEventAdapter::SCROLL_UP : osgGA::GUIEventAdapter::SCROLL_DOWN;
this->getEventQueue()->mouseScroll(motion);
}
virtual bool event(QEvent* event)
{
bool handled = QOpenGLWidget::event(event);
this->update();
return handled;
}
private:
osgGA::EventQueue* getEventQueue() const
{
osgGA::EventQueue* eventQueue = _mGraphicsWindow->getEventQueue();
return eventQueue;
}
osg::ref_ptr<osgViewer::GraphicsWindowEmbedded> _mGraphicsWindow;
osg::ref_ptr<osgViewer::Viewer> _mViewer;
qreal m_scaleX, m_scaleY;
};
int main(int argc, char** argv)
{
// This was necessary for keeping the context when undocking
// without it nothing is shown on the widget when gets undocked
QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
QApplication qapp(argc, argv);
QMainWindow window;
// Here starts code to put the QtOSGWidget inside a dock area
QDockWidget * visDock = new QDockWidget(&window);
visDock->setFloating(false);
visDock->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable);
visDock->setAllowedAreas(Qt::TopDockWidgetArea);
QWidget * dockWidgetContent = new QWidget();
QVBoxLayout * verticalLayout = new QVBoxLayout(dockWidgetContent);
verticalLayout->setSpacing(6);
verticalLayout->setContentsMargins(11, 11, 11, 11);
QWidget * containerWidget = new QWidget(dockWidgetContent);
QHBoxLayout * horizontalLayout = new QHBoxLayout(containerWidget);
horizontalLayout->setSpacing(0);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setContentsMargins(0, 0, 0, 0);
QtOSGWidget* widget = new QtOSGWidget(1, 1, containerWidget);
horizontalLayout->addWidget(widget);
verticalLayout->addWidget(containerWidget);
visDock->setWidget(dockWidgetContent);
window.addDockWidget(static_cast<Qt::DockWidgetArea>(4), visDock);
// No central widget is used for the example
window.setCentralWidget(Q_NULLPTR);
window.show();
return qapp.exec();
}
After _mViewer->setSceneData(geode); add this:
_mGraphicsWindow->init();
initializeGL();
and change the method
virtual void paintGL() {
_mViewer->frame();
}
to
virtual void paintGL() {
_mGraphicsWindow->decrementContextIDUsageCount(_mGraphicsWindow->getMaxContextID());
_mGraphicsWindow->releaseContext();
_mGraphicsWindow->init();
_mViewer->frame();
}
And add thins on main function:
QApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
will solve your problem.

Animation of textview in android

i want to animate textview in such a way that collide with display horizontally and vertically mean while that change random color of text and that runs infinte.is there any way??
i tried like
Animation a = AnimationUtils.loadAnimation(this, R.anim.anim);
a.setFillAfter(true);
a.reset();
tv.startAnimation(a);
i got solution....
MY Solution
textview.xml
<?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"
android:id="#+id/layout">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Helo suni" />
</LinearLayout>
just call repeat function in on create ..
private void repeat() {
// TODO Auto-generated method stub
if (curAnimation == 1) {
animation1 = new TranslateAnimation(width / 2, width, 0, height / 2);
animation1.setDuration(800);
} else if (curAnimation == 2) {
animation1 = new TranslateAnimation(width, width / 2, height / 2, height);
animation1.setDuration(800);
}
else if (curAnimation == 3) {
animation1 = new TranslateAnimation(width / 2, 0, height, height / 2);
animation1.setDuration(800);
}
else if (curAnimation == 4) {
animation1 = new TranslateAnimation(0,width/2,height/2,0);
animation1.setDuration(800);
}
animation1.setFillAfter(true);
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
tv.setTextColor(color);
tv.startAnimation(animation1);
animation1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
if (curAnimation == 4)
curAnimation = 1;
else
curAnimation++;
repeat();
}
});
}

Getting Sprite to fade back in after fade out? Entitiy Modifier

Hi im trying to get a sprite to fade in and scale up after fading out and scaling down. For this i used an Entitiy modifier listener but its not working? Heres my code:
public class GameScene {
Scene gameScene;
Engine engine;
Activity activity;
BitmapTextureAtlas mTextureAtlas;
ITextureRegion X;
ITextureRegion O;
ITextureRegion XO;
FadeInModifier fadeIn = new FadeInModifier(2);
FadeOutModifier fadeOut = new FadeOutModifier(2);
ScaleModifier scaleDown = new ScaleModifier(3, 1, 0);
ScaleModifier scaleUp = new ScaleModifier(2, 0, 1);
Sprite XOsprite;
Random rand = new Random();
boolean XYset = false;
public GameScene(Engine eng, Activity act) {
engine = eng;
activity = act;
}
public Scene getScene() {
gameScene = new Scene();
gameScene.setBackground(new Background(0, 256, 59));
int x = 0, y = 0;
if (rand.nextInt(2) == 0) {
XO = X;
} else {
XO = O;
}
if (!XYset) {
x = rand.nextInt(MainActivity.CAM_WIDTH);
y = rand.nextInt(MainActivity.CAM_HEIGHT);
XYset = true;
}
XOsprite = new Sprite(x, y, XO, engine.getVertexBufferObjectManager()) {
#Override
public boolean onAreaTouched(final TouchEvent te, final float xVal,
final float yVal) {
XOsprite.registerEntityModifier(fadeOut);
XOsprite.registerEntityModifier(scaleDown);
return true;
}
};
IEntityModifierListener fadeOutListener = new IEntityModifierListener() {
#Override
public void onModifierStarted(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
}
#Override
public void onModifierFinished(IModifier<IEntity> pModifier,
IEntity pItem) {
// TODO Auto-generated method stub
XOsprite.clearEntityModifiers();
XOsprite.setPosition(rand.nextInt(MainActivity.CAM_WIDTH), rand.nextInt(MainActivity.CAM_HEIGHT));
XOsprite.registerEntityModifier(fadeIn);
XOsprite.registerEntityModifier(scaleUp);
}
};
fadeOut.addModifierListener(fadeOutListener);
XOsprite.registerEntityModifier(scaleUp);
XOsprite.registerEntityModifier(fadeIn);
gameScene.attachChild(XOsprite);
gameScene.registerTouchArea(XOsprite);
return gameScene;
}
The sprite just fades out and nothing happens. I also want the sprite to change to a random position on the screen when it fades back in. Help?
If you want to do fade in and scale in parallel then you can use use parallelEntityModifier.
Similarly for fade out and scale out parallel then you can use use parallelEntityModifier.
To run these two in sequence use SequenceEntityModifier.
Try this it will work.