How to identify if a view is Button or Textview - android

I have a error function that takes View as an input, and shows error by changing its background to red while there is any problem with view's value as follows -
public static void error(View v) {
v.setBackgroundResource(android.R.color.holo_red_light);
}
I am using this function in another function where I am using it this way -
public static void nonEmptyNonZero(View v) {
String check = "";
check = ((TextView) v).getText().toString();
if ((check.equals(null)) || check.equals("0") || check.equals("")) {
error(v);
}
}
my issue is, that v could be anything (TextView, EditText). So how to identify what is the type of the view. So that I could use proper casting while getting its value using -
check = ((TextView) v).getText().toString();
PS - I have used instanceOf already, I am not sure how casting of a View works.

Like your Views in Object List
List<Object> objectViews=new ArrayList();
views
EditText txtEditText=new EditText();
TextView txtTextView=new TextView();
objectViews.add(txtEditText);
objectViews.add(txtTextView);
traverse to find object (view)
Object view=new Object();
for(int i=0;i<objectViews.size;i++)
{
view.get(i);
if(view instanceof EditText)
{
Log.e("EditText","value="((EditText) view).getText());
}
else if(view instanceof TextView)
{
Log.e("TextView","value="((TextView) view).getText());
}
}

Related

How could I know which "TextView" is clicked

I was creating a dynamic Text View and I need to know which one of those Text views was clicked by the user i read that i need to use getTag() method but it keeps return null when i try it this is my activity code in java:
for(int i=0;i<size;i++){
TextView temp = new TextView(this);
temp.setId(i);
temp.setId(i);
String s = "";
temp.setText(s);
temp.setTextColor(Color.RED);
mylieniarlayout.addView(temp);
tv[i] = temp;
}
final TextView answertv = findViewById(R.id.answertv);
mylieniarlayout.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"ID: "+ v.getTag(), Toast.LENGTH_SHORT).show();
answertv.setText("Clicked ID: " + v.getTag());
}
});
Firstly, setTag() and getTag() methods on view are not used for identifying the view. We use getId() for identifying the view. Please read document here,
getTag on android developers
Secondly, your onClickListner is on layout which won't give you the selected id of textView. In your code you are setting an ID for the text view and trying to fetch a tag which is a mistake.
onClickListener should be on the textview of which you want a tag.
While creating a textView set the tag and then you will get the tag for that textview.
You can try if else condition
Like:
if(v.getTag() == 0){
//Show position 0 here
} else {
//Other position
}
Hope you got your answer

android - How to check if TextView is present in the layout?

I have two different layouts, say layout_1.xml & layout_2.xml. Both layouts have same elements inside it, but layout_2.xml has an additional TextView.
Only one layout will be called according to my needs. I want to perform a check if the textView is available in the layout.
If the TextView is available, it should perform textView.setText(), else the other layout will be called.
Please refer the code below:
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
Picasso.with(mContext).load(singleItem.getUrl()).into(holder.itemImage);
if (holder.lblDescription.getVisibility() == View.VISIBLE){
holder.lblDescription.setText(singleItem.getDescription());
}
}
The TextView holder.lblDescription is in layout_2.xml, but is not present in layout_1.xml.
Therefore, layout_2.xml is running with ease, but when it calls layout_1.xml its giving me this error Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference.
I know, the check I am performing is wrong. So, I need help in this.
Thanks in advance!
Well you are getting a null pointer exception because lblDescription isn't bound to anything in layout_1.xml where it isn't present. So basically what you can do is you can check
if(hold.lblDescription != null){
holder.lblDescription.setText(singleItem.getDescription());
}
instead of
if (holder.lblDescription.getVisibility() == View.VISIBLE){
holder.lblDescription.setText(singleItem.getDescription());
}
/**
* check textview is present or not
*
* #param group : parent layout id
*/
public boolean isTextViewPresent(ViewGroup group)
{
int count = group.getChildCount();
View v;
for (int i = 0; i < count; i++)
{
v = group.getChildAt(i);
if (v instanceof TextView)
{
return true;
} else if (v instanceof ViewGroup)
isTextViewPresent((ViewGroup) v);
}
return false;
}

Android Code does not work / 2 questions

Hello can anybody tell me why this code give me error and crash my app?
This happens only when 'reset((View) child);' is added at the end
What I want to do is when I click a Button with onClick:reset, It will apply a kind of reset to only Images and textviews inside a LinearLayout which has more types of childrens
public void reset(View v) {
LinearLayout items = (LinearLayout) findViewById(R.id.itemsToSearch);
for (int i = 0; i < items.getChildCount(); i++)
{
Object child = items.getChildAt(i);
Context context = getApplicationContext();
CharSequence text = child.toString();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (child instanceof ImageView)
{
((ImageView) child).setVisibility(View.INVISIBLE);
}
else if (child instanceof TextView)
{
((TextView) child).setTextColor(Color.parseColor("#98868A"));
}
else if(child instanceof ViewGroup)
{
reset((View) child);
}
}
}
and the other question is that my app works with FragmentPagerAdapter, How can I do for example if I click a Button in Frag#1 it will change a text inside Frag#3 which is currently not shown?, For me it always crash, As I see it is because Frag#3 or whatever other frag which is off screen is not yet loaded on screen and because of that it doesnt fint the specified ID
Thank You
Your reset method is broken. You are not using the view that is passed as an argument to the method, you are always searching for the same LinearLayout. Your code should look like this:
public void reset(ViewGroup viewGroup) {
final int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ImageView) {
((ImageView) child).setVisibility(View.INVISIBLE);
} else if (child instanceof TextView) {
((TextView) child).setTextColor(Color.parseColor("#98868A"));
} else if(child instanceof ViewGroup) {
// recursive call
reset((ViewGroup) child);
}
}
}
Regarding your other issue, only the current fragment and the ones to either side (within the offscreen page limit, which by default is 1) are actually loaded and in a state where you can manipulate their views. You will need to store some data somewhere and refer back to that data when the page you want (Fragment #3 in your example) is instantiated and you start loading data into it.

How to display validation error for a spinner widget similar to TextView.setError()

How to display validation error for a spinner widget similar to TextView.setError()
I don't want to open a new dialog box for every spinner validation error,
android.widget.Spinner class doesn’t have setError method
If your spinner is set-up with default item views the getSelectedView() method on Spinner class will return a TextView. And on that you can call setError(CharSequence) Here is what I did:
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
TextView selectedTextView = (TextView) selectedView;
if (!valid) {
String errorString = selectedTextView.getResources().getString(mErrorStringResource);
selectedTextView.setError(errorString);
}
else {
selectedTextView.setError(null);
}
}
Result looks like this on Android 4.4:
A somewhat cleaner way of doing Diederik's code:
static public void setSpinnerError(Spinner spinner, String error){
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
TextView selectedTextView = (TextView) selectedView;
selectedTextView.setError(error);
}
}
Just set error to null if you want to dismiss it.
So, you can use 'setError' in your getView in the adapter of spinner. Of course, if your item's xml of your spinner has a TextView:
if(requeriedField && item.getValue() == 0){
img_tittle_spinner.setError(activity.getResources().getString(R.string.FieldRequired));
}

Method to get all EditTexts in a View

can anyone help me with coding a method to get all EditTexts in a view? I would like to implement the solution htafoya posted here:
How to hide soft keyboard on android after clicking outside EditText?
Unfortunately the getFields() method is missing and htafoya did not answer our request to share his getFields() method.
EDIT
MByD pointed me to an error, thus making my answer almost identical to that of blackbelt. I have edited mine to the correct approach.
You could do a for-each loop and then check if each view is of the type EditText:
ArrayList<EditText> myEditTextList = new ArrayList<EditText>();
for( int i = 0; i < myLayout.getChildCount(); i++ )
if( myLayout.getChildAt( i ) instanceof EditText )
myEditTextList.add( (EditText) myLayout.getChildAt( i ) );
You could also, instead of having a list of EditTexts, have a list of ID's and then just add the id of the child to the list: myIdList.add( child.getId() );
To access your layout you need to get a reference for it. This means you need to provide an ID for your layout in your XML:
<LinearLayout android:id="#+id/myLinearLayout" >
//Here is where your EditTexts would be declared
</LinearLayout>
Then when you inflate the layout in your activity you just make sure to save a reference to it:
LinearLayout myLinearLayout;
public void onCreate( Bundle savedInstanceState ) {
super( savedInstanceState );
setContentView( R.layout.myLayoutWithEditTexts );
...
myLinearLayout = (LinearLayout) findViewById( R.id.myLinearLayout );
}
You then have a reference to your the holder of your EditTexts within the activity.
Here's a method I wrote to recursively check all EditText children of a ViewGroup, handy for a long sign-up form I had to do and probably more maintainable.
private EditText traverseEditTexts(ViewGroup v)
{
EditText invalid = null;
for (int i = 0; i < v.getChildCount(); i++)
{
Object child = v.getChildAt(i);
if (child instanceof EditText)
{
EditText e = (EditText)child;
if(e.getText().length() == 0) // Whatever logic here to determine if valid.
{
return e; // Stops at first invalid one. But you could add this to a list.
}
}
else if(child instanceof ViewGroup)
{
invalid = traverseEditTexts((ViewGroup)child); // Recursive call.
if(invalid != null)
{
break;
}
}
}
return invalid;
}
private boolean validateFields()
{
EditText emptyText = traverseEditTexts(mainLayout);
if(emptyText != null)
{
Toast.makeText(this, "This field cannot be empty.", Toast.LENGTH_SHORT).show();
emptyText.requestFocus(); // Scrolls view to this field.
}
return emptyText == null;
}
You can do it by calling View#getFocusables, which will return an arraylist of all focusable views in a View.
Then you can either check if they are EditTexts, with (instanceof) or act on all of them.
This Methods walks recursively through all ViewGroups and collects their TextViews. I use this to assign a new Color to all TextViews (even those embedded in predefined Widgets like Switch etc that make use of TextViews)
private HashSet<TextView> getTextViews(ViewGroup root){
HashSet<TextView> views=new HashSet<>();
for(int i=0;i<root.getChildCount();i++){
View v=root.getChildAt(i);
if(v instanceof TextView){
views.add((TextView)v);
}else if(v instanceof ViewGroup){
views.addAll(getTextViews((ViewGroup)v));
}
}
return views;
}
Get all Edit Text in any type of layout.
public List<EditText> getAllEditTexts(ViewGroup layout){
List<EditText> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof EditText){
views.add((EditText)v);
}
}
return views;
}

Categories

Resources