how to get label from custom tablayout? - android

I am creating tabs with icons and text using ,
private void setupTab() {
int i = 0;
for (Map.Entry<String, Integer> entry : tabvalues.entrySet()) {
try {
TextView tabView = (TextView) LayoutInflater.from(baseActivity).inflate(R.layout.custom_tab, null);
tabView.setText(entry.getKey());
tabView.setCompoundDrawablePadding(10);
tabView.setCompoundDrawablesWithIntrinsicBounds(0, entry.getValue(), 0, 0);
tabLayout.getTabAt(i).setCustomView(tabView);
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
now I wnt to get the text of the tab,
tabLayout.getTabAt(position).getText().toString();
It is returning null.

You can try:
((TextView)tabLayout.getTabAt(position).getCustomView()).getText().toString();

Related

Dynamic Spinners item selection error

I' am creating and populating spinners dynamically,the problem is while selecting the items(eg:4th) of any spinner ,i'am getting the id of the last spinners which is created dynamically item(4th id). I want to get the corresponding id's which i was set dynamically to the spinner items.
How to get the values of each spinner correctly..
Codes are give below.
public void secondarray(JsonParser jsonParser) {
String fieldName;
ameList = new ArrayList<AmeModel>();
AmeModel ameModel = null;
try {
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
ameModel = new AmeModel();
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
fieldName = jsonParser.getCurrentName();
if ("valueid".equals(fieldName)) {
jsonParser.nextToken();
ameModel.setId((jsonParser.getText()));
} else if ("valuename".equals(fieldName)) {
jsonParser.nextToken();
ameModel.setName((jsonParser.getText()));
} else {
jsonParser.skipChildren();
}
}
ameList.add(ameModel);
}
Spinner sp=new Spinner(MainActivity.this);
AmeAdapter adapter = new AmeAdapter(this, ameList);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this, ameList.get(i).getId(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
container.addView(sp);
//setContentView(linearlayout);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Any help will be appreciated thank you.
For get selected item Name:
String itemName=sp.getSelectedItem().toString(); // sp is your spinner
For get selected item position :
int position = sp.getSelectedItemPosition();
Now as per your code snippiest If you want to get Id Those you have set dynamically.
HashMap<String, String> nameId;
String itemId;
String itemName= String.valueOf(sp.getSelectedItem());
for (String s : nameId.keySet()) {
if (nameId.get(s).equals(itemName)) {
itemId= s;
}
Try to use above suggestion

How to get color of Toolbar's/ActionBar's text color programmatically?

I'm trying to get toolbar's textColor using this method:
private int getToolbarTextColor() {
int toolbarTextColor;
TypedArray typedArray = getTheme().obtainStyledAttributes(new int[]{R.attr.titleTextColor});
try {
toolbarTextColor = typedArray.getColor(0, Color.TRANSPARENT);
} catch (UnsupportedOperationException e) {
toolbarTextColor = Color.TRANSPARENT;
} finally {
typedArray.recycle();
}
return toolbarTextColor;
}
but it returns 0. What is the problem in my code? What attribute should I use? Is there another better way to get it?
Here is a method that uses reflection for obtaining a Toolbar title TextView's color:
#ColorInt public static int getToolbarTitleTextColor(Toolbar toolbar) {
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
TextView mTitleTextView = (TextView) f.get(toolbar);
if (mTitleTextView != null) {
return mTitleTextView.getCurrentTextColor();
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;}
val a = TintTypedArray.obtainStyledAttributes(context, null, R.styleable.Toolbar, R.attr.toolbarStyle, 0);
title.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))
subtitle.setTextColor(a.getColor(R.styleable.Toolbar_titleTextColor, -0x1))
(Kotlin)

Change text style / size of selected value in NumberPicker

I've got two problems to custom my numberpicker on my application. After lot of research I didn't found anything that help me.
First is that I want increase the selected text. I already have a class that extends number picker to customize the general text size, font and divider visibility, but I'm not able to increase only the selected value.
Second problems, I want to put some unicode on my text, so I'm trying to use a spannableString[] instead of String[] for the formattter, but nothing seems to work. I would use Spannable to be able to change the police font of a little part of my text (With some Regex)
Is there a way to do this ?
What I've done actually :
public class MyNumberPicker extends NumberPicker{
private Context context;
public MyNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
#Override
public void addView(View child) {
super.addView(child);
updateView(child);
}
#Override
public void addView(View child, int index, android.view.ViewGroup.LayoutParams params) {
super.addView(child, index, params);
updateView(child);
}
#Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
super.addView(child, params);
updateView(child);
}
private void updateView(View view) {
if(view instanceof EditText){
//Text size
((EditText) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
//Text font
Typeface robotoFont = FontCache.get("fonts/Roboto-Regular.ttf", getContext());
((EditText) view).setTypeface(robotoFont);
}
//Non visible selectors
java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (java.lang.reflect.Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try {
ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(
getContext(), R.color.colorTransparent
));
pf.set(this, colorDrawable);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
}
}
THe formatter :
npTemp.setMinValue(0);
npTemp.setMaxValue(values.length - 1);
NumberPicker.Formatter formatter = new NumberPicker.Formatter() {
#Override
public String format(int value) {
return values[value];
}
};
npTemp.setFormatter(formatter);
What I've tried to get the selected value EditText on my custom Number picker
java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (java.lang.reflect.Field pf : pickerFields) {
if (pf.getName().equals("mInputType")) {
pf.setAccessible(true);
try {
((EditText)pf).setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
And to have SpannableString, I've done lot of things but the formatter only want String.
Thanks for helping

Show dropdown after dynamic loading

I load dynamically the string of my autocomplete with JSON objects, but the list appears only in the next character; How can I make my list appear exactly after the loading?
This process is called from a onTextChanged event. I tried to force display with showDropDown() but didn't work!!!
Any help?
public class HttpConnectionApiActivity extends Activity implements HttpListner, TextWatcher {
.....
AutoCompleteTextView from_txt;
List<String> country_List;
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
from_txt = (AutoCompleteTextView) findViewById(R.id.from_txt);
//from_txt.setThreshold(1);
prepareCountryList();
from_txt.addTextChangedListener( this);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,country_List);
from_txt.setAdapter(adapter);
}
....
public void notifyHTTPRespons(final HttpHandler http) {
public void run() {
String result = http.getResponse();
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I could display the dropdown list by adding these 2 lines :
It's very simple hack by resetting text when you get updated data.
try {
adapter.clear();
for (int i = 0; i < results_Array.length(); i++) {
JSONObject row = results_Array.getJSONObject(i);
String name=row.getString("name");
adapter.add(name);
}
//____________________
adapter.notifyDataSetChanged();
from_txt.setText(from_txt.getText());
//____________________
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Android ORMLite - ForeignCollection child has null foreign field

I'm currently stuck with the following situation;
Basically I've got a Work class, which has a ForeignCollection of WorkTasks.
I'd like to simply receive all WorkTasks, linked to Work object.
If I query for all WorkTasks, I do get a list of results but with 'work = null'. So it can't make any link to the correct Work object.
Resulting in no results with querying for the work_id and an empty list in Work itself.
I've seen examples and questions about this countless of times but apparently im missing out on something.
Below is the code that im using which is relevant;
The DatabaseHelper;
#Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
applicantDao = DaoManager.createDao(connectionSource, Applicant.class);
educationDao = DaoManager.createDao(connectionSource, Education.class);
workDao = DaoManager.createDao(connectionSource, Work.class);
workTaskDao = DaoManager.createDao(getConnectionSource(), WorkTask.class);
onlinePersonDao = DaoManager.createDao(connectionSource, OnlinePerson.class);
institutionDao = DaoManager.createDao(connectionSource, Institution.class);
lessonDao = DaoManager.createDao(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, Applicant.class);
TableUtils.createTable(connectionSource, Education.class);
TableUtils.createTable(connectionSource, Work.class);
TableUtils.createTable(connectionSource, Institution.class);
TableUtils.createTable(connectionSource, Lesson.class);
TableUtils.createTable(connectionSource, OnlinePerson.class);
TableUtils.createTable(connectionSource, Reference.class);
TableUtils.createTable(connectionSource, WorkTask.class);
[....]
public Dao<WorkTask, Integer> getWorkTaskDao() {
if (null == workTaskDao) {
try {
workTaskDao = getDao(WorkTask.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return workTaskDao;
}
The database manager:
public List<Experience> getAllWork() {
List<Experience> exp = null;
try {
exp = getHelper().getWorkDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return exp;
}
public List<WorkTask> getAllWorkTask() {
List<WorkTask> workTask = null;
try {
workTask = getHelper().getWorkTaskDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return workTask;
}
public List<WorkTask> getWorkTaskByWorkId(int workId) {
List<WorkTask> workTasks = null;
try {
workTasks = getHelper().getWorkTaskDao().queryForEq("work_id", workId);
} catch (SQLException e) {
e.printStackTrace();
}
return workTasks;
}
public void addWork(Collection<Work> jobs) {
try {
for (Experience work : jobs) {
Work w = (Work) work;
// Add nested child first
this.addInstitution(w.institution);
this.addWorkTask(w.tasks);
getHelper().getWorkDao().createOrUpdate(w);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addWorkTask(Collection<WorkTask> worktasks) {
try {
for (WorkTask wt : worktasks) {
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
The list from the work model (gets a pre-filled id from an abstract parent):
#ForeignCollectionField(eager = true)
#SerializedName("tasks")
public Collection<WorkTask> tasks;
public ArrayList<WorkTask> getTasks(){
ArrayList<WorkTask> taskList = new ArrayList<WorkTask>();
Iterator iterator = tasks.iterator();
while(iterator.hasNext()){
WorkTask task = (WorkTask) iterator.next();
taskList.add(task);
}
return taskList;
}
The WorkTask :
public class WorkTask {
/**
* Auto-incremented id for the ORMLite-SQLite database
*/
#DatabaseField(generatedId = true)
public int id;
/**
* Foreign field id for the ORMLite-SQLite database
*/
#DatabaseField(foreign = true, foreignAutoCreate = true, foreignAutoRefresh = true, columnName = "work_id")
public Work work;
And finally all the things that are failing me:
ArrayList<WorkTask> tasks_iterated = work.getTasks();
ArrayList<WorkTask> tasks_id = (ArrayList<WorkTask>) DatabaseManager.getInstance()
.getWorkTaskByWorkId(work.id);
ArrayList<WorkTask> tasks = (ArrayList<WorkTask>) DatabaseManager.getInstance().getAllWorkTask();
This eventually leaves me with:
tasks_iterated = empty
tasks_id = empty
tasks = a full list of my tasks but all with the attribute 'work = null' so I can't place them to the correct Work object.
Fixed it by changing my adding method to:
public void addWorkTask(Collection<WorkTask> worktasks, Work work) {
try {
for (WorkTask wt : worktasks) {
wt.work = work;
getHelper().getWorkTaskDao().createOrUpdate(wt);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Not sure if it's the only way to do this though. Seems a bit weird i'd have to do this manually.

Categories

Resources