Add onclick at more then one object - android

I create a button for each name in my database, then i should add at this button a onclick function, but i don't know what id use. i use ??? in the code for indicate the position
public class Game extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
ListView playersList=(ListView)findViewById(R.id.playersList);
MyDb db=new MyDb(getApplicationContext());
db.open();
Cursor c=db.fetchAllUsers();
startManagingCursor(c);
SimpleCursorAdapter adapter=new SimpleCursorAdapter(
this,
R.layout.user,
c,
new String[]{MyDb.UsersMetaData.USERS_NAME},
new int[]{R.id.namePlayer}
);
playersList.setAdapter(adapter);
db.close();
Button newUser;
newUser = (Button)findViewById(R.id.buttonNew);
newUser.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MyDb db=new MyDb(getApplicationContext());
db.open();
EditText inserted = (EditText)findViewById(R.id.editName);
String nome = inserted.getText().toString();
db.insertUser(nome);
db.close();
}
});
Button chosen;
chosen = (Button)findViewById(R.id.???);
chosen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Game2.class);
startActivityForResult(myIntent, 0);
finish();
}
});
}
}
user interface
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sfondo"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#drawable/sfondo">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<EditText
android:id="#+id/editName"
android:text="#string/editName"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:lines="1"
android:width="180px" />
<Button
android:text="#string/newPlayer"
android:id="#+id/buttonNew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="70px" />
</LinearLayout>
<ListView
android:id="#+id/playersList"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</FrameLayout>
xml for the db elements
<?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:layout_gravity="center_vertical"
>
<Button
android:id="#+id/namePlayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:minWidth="250px" />
</LinearLayout>
thanks

So the button is in R.layout.user? If so I think you may need to extend SimpleCursorAdapter and in the getView() method you can find the view and add the listener. Something like this:
public class MyCursorAdapter extends SimpleCursorAdapter {
public MyCursorAdapter(...) {
super(...);
}
public void getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Button button = (Button) view.findViewById(R.id.???);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
...
}
});
}
}
That way your 'find' is scoped to one row in the list. You can't add the listener where you have the code currently because there will be multiple Views with the same ID.

to define onClick to more than one object , your class should implement the interface OnClickListener , and override the method onClick(View v) , like this :
public class MyActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstance){
....
//add listeners to your buttons
btn1.setOnClikListener(this);
btn2.setOnClickListener(this);
....
}
#Override
public void onClick(View v ) {
if(v==btn1)
// treatement 1
if(v== btn2)
//treatment 2
...etc
}

Related

Android: Exit full screen and return to main activity

Main activity contains a spinner and a button. MainActivity.java code is as follows.
public class MainActivity extends AppCompatActivity implements LoadNew.VCallback {
public Spinner dropdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dropdown = (Spinner) findViewById(R.id.spinner1);
//Create a list of items for the spinner.
String[] items = new String[]{"select topic", "topic1", "topic2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// TODO Auto-generated method stub
String sp1 = String.valueOf(dropdown.getSelectedItem());
if (sp1.contentEquals("select topic")) {
loadFun("");
}
if (sp1.contentEquals("topic1")) {
loadFun("topic1");
}
if (sp1.contentEquals("topic2")) {
loadFun("topic2");
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView){
// TODO Auto-generated method stub
}
});
Button x = (Button) findViewById(R.id.full_screen);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFun("topic2", 0);
}
});
}
public void loadFun(String topicName, int i) {
LoadNew st = new LoadNew(this);
st.display(topicName, i);
}
}
The xml layout for main activity is as follows (activity_main.xml).
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/full_screen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Full Screen"
style="?android:attr/borderlessButtonStyle"/>
</LinearLayout>
<LinearLayout
android:id="#+id/full_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
</RelativeLayout>
There is another java class LoadNew.java as follows.
public class LoadNew {
public interface VCallback {
//To access methods of MainActivity class
}
public Activity activity;
public LoadNew(Activity _activity) {
this.activity = _activity;
VCallback callerActivity = (VCallback) activity;
}
//Display PDF
public void display(String topicName, int i) {
LinearLayout fullScreen = (LinearLayout) this.activity.findViewById(R.id.full_view);
fullScreen.removeAllViews();//Clear field
LayoutInflater inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_load, null);
if(i ==0) {
this.activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.activity.setContentView(view);
}
TextView tv= (TextView) this.activity.findViewById(R.id.tv1);
tv.setText(topicName);
tv.setTextSize(100);
}
}
The activity_load.xml file is as follows.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout> xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tv1"
android:layout_below="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
When an item is selected in the spinner, the corresponding text is displayed in the textview. Upon pressing the button, the textview appears in full screen mode.
Now I want to return to the previous view (by pressing back button or by single tab on screen), i.e., the view before the button was clicked. How can I achieve this? Thanks in advance for the patience and the help.
Simplest would be to have the spinner and the non-fullscreen TextView on one activity and open a second activity with the fullscreen mode on button click.

Can't dismiss a custom DialogFragment Android

I implemented my own DialogFragment with my custom layout, with two simple buttons. The problem is that I am not able to dismiss it. Here there is the code of the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:l
ayout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgProfileQuestionSender"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/questionToAnswer"
android:layout_gravity="center_horizontal"
android:padding="10dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/yes"
android:id="#+id/yesButtonAnswer"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/no"
android:id="#+id/noButtonAnswer"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
here there is the code of my Dialog
public class QuestionDialog extends DialogFragment implements View.OnClickListener {
public interface QuestionInterface{
void yesQuestionPressed(int idQuestion);
void noQuestionPressed(int idQuestion);
}
private int idQuestion;
private QuestionInterface mQuestionInterface;
//private DialogInterface.OnClickListener mOnclickListener;
private Button yesButton, noButton;
private ImageView profileImage;
private TextView question;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.layout_dialog_question, null);
noButton = (Button)view.findViewById(R.id.noButtonAnswer);
yesButton = (Button)view.findViewById(R.id.yesButtonAnswer);
profileImage = (ImageView)view.findViewById(R.id.imgProfileQuestionSender);
question = (TextView)view.findViewById(R.id.questionToAnswer);
question.setText("here there should be the text of the question retrived using the id of the question, also the image on the left should be the image of" +
"the friend that sent the question, the id of the question is " + String.valueOf(getArguments().getInt("questionId")));
Picasso.with(getActivity().getApplicationContext()).load("http://i.imgur.com/DvpvklR.png").transform(new CircleTransform()).fit().centerCrop().into(profileImage);
setCancelable(false);
return view;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.yesButtonAnswer){
dismiss();
mQuestionInterface.yesQuestionPressed(getArguments().getInt("questionId"));
}
if(v.getId()==R.id.noButtonAnswer){
dismiss();
mQuestionInterface.noQuestionPressed(getArguments().getInt("questionId"));
}
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if(activity instanceof QuestionInterface) {
mQuestionInterface = (QuestionInterface) activity;
}
}
Directly set your Button Click Listener in onCreateView(...)
#Override
public View onCreateView(....)
{
.......
.......
negativeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
positiveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
.......
}

Catching onClick events in child view of a list item

How can I catch onClick events in multiple child views of a list item in a ListFragment with custom Adapter?
I want the onClick event to return the item id and the child view id.
My list item layout is.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:id="#+id/event_status" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="7dp"
android:nestedScrollingEnabled="false">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/event_members" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/event_date"/>
</LinearLayout>
</LinearLayout>
I want to catch clicks on event_status and event_members separately.
I personnaly use android left side menu, which manages different fragments by clicking on a custom adapter
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I think the interesting part for you is
myList.setOnItemClickListener(new myItemClickListener());
then
private class myItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your code
}
}
Hope this can help
You can do it like this
private class YourAdapter extends ArrayAdapter<...>
{
TextView event_date = (TextView) convertView.findViewById(R.id.event_date);
event_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
TextView event_members = (TextView) convertView.findViewById(R.id.event_members );
event_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
What might also work, but I think there is no benefit in doing it like this and seems not clean:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// the same two handler here
TextView event_members = (TextView) convertView.findViewById(R.id.event_members );
event_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}

Show my Fragment in Dialog android

I have a class that extends a Fragment. I want when press a button from An Activity to opens this Fragment with its layout in dialog in addition to that the fragment opens normally in its place. Is this possible?
This is my Fragment (TipsFragment.java)
public class TipsFragment extends Fragment{
ListView list;
TipsAdapter tipsAdapter;
AlertDialog PageDialog;
DAO db;
Cursor c;
ArrayList<HashMap<String, String>> tipsList;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> pages;
Integer tipType;
ImageButton page;
ImageButton add;
ImageButton search;
EditText inputAdd;
EditText inputSearch;
ImageView addImage;
RelativeLayout layoutAdd;
RelativeLayout layoutSearch;
int itemSelected;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = new DAO(activity);
db.open();
}
public TipsFragment(){}
public TipsFragment(int tipType, int itemSelected ){
this.tipType = tipType;
this.itemSelected = itemSelected;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tips_fragement, container, false);
System.out.println("tipType: "+tipType);
System.out.println("itemSelected: "+itemSelected);
page = (ImageButton) rootView.findViewById(R.id.pager);
add = (ImageButton) rootView.findViewById(R.id.add);
search = (ImageButton) rootView.findViewById(R.id.search);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
inputAdd = (EditText) rootView.findViewById(R.id.inputAdd);
addImage = (ImageView) rootView.findViewById(R.id.imageAdd);
layoutAdd = (RelativeLayout) rootView.findViewById(R.id.layoutAdd);
layoutSearch = (RelativeLayout) rootView.findViewById(R.id.layoutSearch);
if (tipType != 0) {
switch (tipType) {
case 1:
System.out.println("All tips");
if (getActivity().getIntent().getStringExtra("startFrom") == null) {
c = db.getTips("0");
} else {
c = db.getTips(getActivity().getIntent().getStringExtra("startFrom"));
}
break;
case 2:
System.out.println("favorite tips");
c = db.getFavoriteTips();
page.setVisibility(View.GONE);
System.out.println("in favorite, count_records: "+c.getCount());
break;
}
}
System.out.println("count_records: "+c.getCount());
if (c.getCount() != 0) {
if (getActivity().getIntent().getStringExtra("startLabel") != null) {
page = (ImageButton) rootView.findViewById(R.id.pager);
}
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
// Getting adapter by passing xml data ArrayList
tipsAdapter = new TipsAdapter(getActivity(), tipsList);
list.setAdapter(tipsAdapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
map = tipsList.get(position);
System.out.println("in list select item, tipType: "+tipType);
if (!MainActivity.tSlidingLayer.isOpened()) {
MainActivity.tSlidingLayer.openLayer(true);
}
}
});
page.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Strings to Show In Dialog with Radio Buttons
}
});
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
inputSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
addImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "addImage pressed", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
and this is layout tips_fragement.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/titleBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/add"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/add" />
<ImageButton
android:id="#+id/search"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/search" />
<ImageButton
android:id="#+id/pager"
android:layout_width="45dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:scaleType="fitXY"
android:src="#drawable/pager" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dip"
android:background="#drawable/shadow" >
</View>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layoutAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" >
<EditText
android:id="#+id/inputAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Add" />
<ImageView
android:id="#+id/imageAdd"
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/inputAdd"
android:layout_alignBottom="#+id/inputAdd"
android:layout_alignRight="#+id/inputAdd"
android:src="#android:drawable/ic_menu_add" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/layoutSearch"
android:visibility="gone" >
<EditText
android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search"/>
<ImageView
android:id="#+id/imageSearch"
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/inputSearch"
android:layout_alignBottom="#+id/inputSearch"
android:layout_alignRight="#+id/inputSearch"
android:src="#android:drawable/ic_menu_search" />
</RelativeLayout>
<ListView
android:id="#+id/tipList"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttons"
android:divider="#351802"
android:dividerHeight="2dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
Since Android supports nesting Fragments (available in the support library) you could show your TipsFragment as a content of another DialogFragment. Avoid this solution whenever possible.
A better solution would be to make TipsFragment extend DialogFragment and that way you can either show the Fragment inline or in a dialog.
1 - Make TipsFragment extends DialogFragment
public class TipsFragment extends DialogFragment {...}
2 - On button click use FragmentTransaction.add or FragmentTransaction.replace to show the DialogFragment inline or include it in your layout and change its visibility.
3 - Show the TipsFragment as a dialog
TipsFragment fr = new TipsFragment();
fr.show(getSupportFragmentManager(), "dialog_fragment_tag");
Guide: Performing Fragment Transactions. More samples are available in the ApiDemos application from the SDK samples

How do I repeat an existing xml spinner dynamically

I have an XML file: my_form.xml (abridged to just show relevant views). The spinner is populated by a string array from strings.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Spinner
android:id="#+id/task"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/task_array"
android:prompt="#string/task" />
<TextView android:id="#+id/addTask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add another task"
android:onClick="onClick"
android:clickable="true"/>
</LinearLayout>
</ScrollView>
So I have an activity that displays the xml spinner and text view.
When the text view is clicked I want to add another instance of the same xml spinner and text view, so that a person can add as many tasks as they like.
I dont want a multi-select listView as I am going to have to associate each chosen item/task with other individual methods
Can anyone help me please?
public class MyFormActivity extends FragmentActivity implements
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_form);
final Spinner spinnerTask = (Spinner) findViewById(R.id.task);
ArrayAdapter<CharSequence> adapter_task = ArrayAdapter
.createFromResource(this, R.array.task_array,
android.R.layout.simple_spinner_item);
spinnerTask.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long row) {
int taskChoice = spinnerTask.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",
0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("taskChoiceSpinner", taskChoice);
prefEditor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
View tvAddTask = (TextView) findViewById(R.id.addTask);
tvAddTask.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here I want add another instance of the spinner and text view above
}
}
Try this
1 - Edit my_form.xml to this
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayout01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
2 - Create new layout xml file text_view.xml and put this in it
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add another task"
android:clickable="true"/>
3 - Create new layout xml file spinner_view.xml and put this in it
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/task_array"
android:prompt="#string/task" />
4 - Edit your code like this
public class MyFormActivity extends FragmentActivity implements OnClickListener {
private LinearLayout linear;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_form);
linear = (LinearLayout) findViewById(R.id.LinearLayout01);
addNewView();
}
private void addNewView(){
Spinner spinnerTask = View.inflate(this, R.layout.spinner_view, null);
TextView tvAddTask = View.inflate(this, R.layout.text_view, null);
linear.addView(spinnerTask);
linear.addView(tvAddTask);
spinnerTask.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long row) {
int taskChoice = pos;
SharedPreferences sharedPref = getSharedPreferences("FileName",
0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("taskChoiceSpinner", taskChoice);
prefEditor.commit();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
tvAddTask.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here I want add another instance of the spinner and text view above
addNewView();
}
});
}
}
Hope this helped you.
You could just write a method that would call the spinner and this method would get called in the spinner.setOnItemSelectedListener();

Categories

Resources