So, I have a spinner with two different options thus far. What I am trying to accomplish is, if "First Spinner Option" is chosen, then I setContentView to a specific layout and execute code corresponding to that layout. The same goes if "Second Spinner Option" is chosen. I know that I need to use setOnItemSelectedListener to a certain extent, but I am not sure how this would work exactly. Below is a quick mock up of what I'm trying to do in coding terms
spinner.setonItemSelectedListener(this);
if(spinner = first spinner option){
setContentView(R.layout.lay1);
//other code here
}elseif(spinner = second spinner option){
setContentView(R.layout.lay2);
//other code here
}
I know the syntax is bad here, Im just trying to get a general idea of how this could be done.
EDIT: #CodeMagic
This is how my code is setup thus far. 'items' is just an array of strings with 2 elements.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.my_spinner_style, items) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Exo-Bold.otf");
((TextView) v).setTypeface(tf);
return v;
}
public View getDropDownView(int position, View convertView, ViewGroup parent) {
View v =super.getDropDownView(position, convertView, parent);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Exo-Bold.otf");
((TextView) v).setTypeface(tf);
//v.setBackgroundColor(Color.GREEN);
return v;
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gasChoice.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
}
public void addListenerOnSpinnerItemSelection(){
gasChoice = (Spinner) findViewById(R.id.gasChoice);
gasChoice.setOnItemSelectedListener(new OnItemSelected());
}
I don't know exactly what the problem is you are having but its pretty close. You just need to add the method
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView tv = (TextView)arg1; // get the TextView selected
String text = tv.getText().toString();
if(text.equals("FirstText")){ // compare the text in the box
setContentView(R.layout.lay1);
//other code here
}elseif(text.equals("FirstText")){
setContentView(R.layout.lay2);
//other code here
}
}
There are different ways of doing this such as getting the position (arg2) and comparing that to what's in your adapter but since I don't know how you are doing any of that, this is the easiest way to get you started.
Related
Hey guys I am pretty new to android programming and I have a few questions. I hope somebody can help.
I am using the code:
new ArrayAdapter<Customer> (this, android.R.layout.simple_list_item_multiple_choice,emptyListForInitialization) {...
But I want to use my own layout I created ("R.layout.custom_customer_layout").
I can use it, if I CHANGE the code-line with:
new ArrayAdapter<Customer> (this, android.R.layout.simple_list_item_multiple_choice,emptyListForInitialization)
with my layout ("R.layout.custom_customer_layout")
AND REMOVE THE CODE
View view = super.getView(position, convertView, parent);
And UNCOMMENT the section (code between /* ... */ ) below it.
But I don't get the getView-Method.
WHY DO I HAVE TO REFER TWICE TO MY LAYOUT?
First time during creating the new ArrayList
Second time in the getView-Method???
This is the important part of my code:
private ListView myTestListView;
private void initializeCustomerListView() {
myTestListView = (ListView) findViewById(R.id.listview_customers);
List<Customer> emptyListForInitialization = new ArrayList<>();
ArrayAdapter<Customer> customerArrayAdapter = new ArrayAdapter<Customer> (
this, android.R.layout.simple_list_item_multiple_choice,
emptyListForInitialization) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
/*
View view = getLayoutInflater().inflate(R.layout.custom_customer_layout,null);
TextView textViewName = (TextView)convertView.findViewById(R.id.textView20);
TextView textViewContact = (TextView)convertView.findViewById(R.id.textView21);
TextView textViewMobile = (TextView)convertView.findViewById(R.id.textView25);
textViewName.setText(this.getItem(position).getCustomerName());
textViewContact.setText(this.getItem(position).getCounterpart());
textViewMobile.setText(this.getItem(position).getMobilePhoneNumber());
*/
return view;
}
};
myTestListView.setAdapter(customerArrayAdapter);
}
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0;i<showLists.size();i++){
//
TextView v=(TextView)listContent.getChildAt(i).findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
TextView v=(TextView)listContent.getChildAt(position).findViewById(R.id.txtDes);
v.setTextColor(Color.RED);
Toast.makeText(context,"POS "+showLists.get(position).getDes(),Toast.LENGTH_SHORT).show();
}
});
I have been the problem with get position item of listview. Android just has shown about 12 row on devide's creen, when I click another item on listview (my listview have 30 item ) which shown the error.
And this is error:
"Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference" .
Thanks for read.
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i < showLists.size(); i++) {
TextView v = (TextView) view.findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
TextView v = (TextView) view.findViewById(R.id.txtDes);
v.setTextColor(Color.RED);
Toast.makeText(context, "POS " + showLists.get(position).getDes(), Toast.LENGTH_SHORT).show();
}
});
Your question is indeed about Null Pointer Exception, but is harder to identify why this is happening. The problem can be found here:
for(int i=0;i<showLists.size();i++){ <-- this line actually causes the crash
//
the crash is in the next line, at the findViewById
TextView v=(TextView)listContent.getChildAt(i).findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
Your for has the wrong upper limit because of a mechanism known as recycling, and because of this mechanism your list view will never have the same number of rows as the amount of data that needs to be displayed (read about recycling to understand this). Given this fact, we know for sure that the number of views found in list view (listContent.getChildCount()) will be smaller than showLists.size() and thus making the call listContent.getChildAt(i) to return a NULL value when the index equals listContent.getChildCount() creating the crash.
Now you might be tempted to change showLists.size() with listContent.getChildCount() and see that the app doesn't crash anymore, but if you click a row, then other rows are coloured also as you scroll the list (the recycling is again the problem). To really fix the problem you should save the index of the selected row and call notifyDatasetChanged, so when getView is called in adapter you simply check the current position to be displayed with the selected position. In case of equality you change the color of text to red, otherwise to black. Below, you will find some parts of an example:
int currentPosition = -1;
// Just a basic adapter. The getView method is the key here
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) {
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position == currentPosition) {
((TextView) view).setTextColor(Color.RED);
} else {
((TextView) view).setTextColor(Color.BLACK);
}
return view;
}
};
// and here is the onItemClick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentPosition = position;
adapter.notifyDataSetChanged();
}
});
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewRow=convertView;
if(viewRow==null){
viewRow=inflater.inflate(layout,parent,false);
viewHolder viewHolder=new viewHolder();
viewHolder.imgIcon = (ImageView) viewRow.findViewById(R.id.imgIcon);
viewHolder.txtDes = (TextView) viewRow.findViewById(R.id.txtDes);
viewRow.setTag(viewHolder);
}
viewHolder holder= (viewHolder) viewRow.getTag();
holder.imgIcon.setImageResource(listMoiNhat.get(position).getIcon());
holder.txtDes.setText(listMoiNhat.get(position).getDes());
if(position==currentpos){
holder.txtDes.setTextColor(Color.RED);
}
else {
holder.txtDes.setTextColor(Color.RED);
}
return viewRow;
}
//and here is create customListMoiNhat object
final customListMoiNhat customListMoiNhat=new customListMoiNhat(context,R.layout.moinhat_customlistview,showLists,currentpos);
customListMoiNhat.notifyDataSetChanged();
listContent.setAdapter(customListMoiNhat);
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentpos=position;
customListMoiNhat.notifyDataSetChanged();
}
});
So in my listview I have a bunch of strings, but I'd like to display the values with £ in front of the strings, but NOT actually edit the values themselves in the ArrayList.
Anyone know how I can do this?
I'm already overwriting the view anyway, I'm just not sure how to alter the display of the items values themselves.
Some Code:
adapter = (new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItems) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 != 0)
view.setBackgroundColor(Color.rgb(135,206,250)); // Pale blue
return view;
}
});
foodListView = (ListView) findViewById(R.id.foodListView);
foodListView.setAdapter(adapter);
In you getView method you can use:
TextView text = (TextView) view.findViewById(android.R.id.text1);
text.setText("£" + listItems.get(position));
I just set up my ArrayAdapter to convertView to my favor , but now I wonder how to control the children of the LinearLayouts am using in that listview , lets say I have a TextView in the Linearlayout , I want to call setText , but I don't know how , or maybe I have a button which I want to call setOnClickListener , I don't know how !
Here is my getView code :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null){
convertView = inf.inflate(R.layout.normal_row, parent , false);
}
switch(position){
case(0):
// here is where my first LinearLayout goes , containing an Image and Switch which I need to program in onCheckedChangeListener ...
convertView = (LinearLayout) inf.inflate(R.layout.row_switch, parent,false);
break;
case(1)
// here I need to set the Text for the following two options on some basis , they are both linearLayouts containing a single textView which I want to call setText for each case 1 and 2.
break;
case(2)
}
TextView textview = (TextView) convertView.findById(R.id.txt);
text.setText("textview");
Button btn = (Button) convertView.findById(R.id.btn);
btn.setTag(textview);
btn.setOnClickListener(...)
{
onClick(..){
TextView t = (Textview)btn.getTag():
t.setText("new value")
}
}
i suggest you to look at the question which i replied before.
Let's say your normal_row layout has a TextView in it with the id #id/my_text_view. Then you would set the text like
TextView view = (TextView) convertView.findViewById(R.id.my_text_view);
view.setText("Some text");
You can access anything in the layout you've inflated by its id in a similar way.
One thing to note though is there seem to be two types of views that you're inflating. Let's say that you try to use the code I gave you, but my_text_view is only in normal_row. Then if you've inflated the row_switch view, the findViewById() will return null because it can not find a view with the given id.
Use onItemClick and find your view by the view that the OnItemClickListener provides you!
For example: `mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});`
By the passed View find your textview or your button inside every listView children.
Example: TextView tempTextView = (TextView) arg1.findViewById(R.id.myTextView);
The id of the textview is the one you assigned to it in your inflated layout for every row!
I want to override the text colour in the android adapter, how can I do that. The values of the string will be loaded from backend service.
Plz help me out.
lv = (ListView) findViewById(R.id.report_symptomlv);
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, mSymptoms);
lv.setAdapter(mAdapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
//--------------
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mName = input.getText().toString().toUpperCase();
//----I need to make this text as Orange----
Geocoder mGeoCoder = new Geocoder(favorite.this, Locale.getDefault());
Try this...
- I believe a Code is better than thousand Words, but still some guys need more than that, and so i would like to explain it....
- You will need to use getView() method that will be in used to defining the attributes of the inflated views in the ListView.
ArrayAdapter<String> adpt = new ArrayAdapter<String>(ReferralsActivity.this, android.R.layout.simple_list_item_1,numList){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,20);
((TextView) v).setTextColor(Color.BLACK);
return v;
}
};
Use a custom Listview. You will have more flexibility in inflating the views and styling them. For custom listview have a look at this link. http://www.androidpeople.com/android-custom-listview-tutorial-part-1.