I have some question regarding Android programming. More specific, I have a ListView where every single row is containg five widgets and each trigger event. I have created custom adapter and defined events handler for every widgets in the getView method. Everything works fine, however the code looks quite long, unreadable and nasty because of all these event handlers inside. Is there any better design? Maybe Creating event handlers outside the getView method or something else?
greetings
According to suggestion I posted part of the source code. As you can see I have created few event handlers outside the getView method and two inside. I really do not know which design is better.
public class ListViewAdapter extends ArrayAdapter<HourReport> {
private static Activity context;
private int resourcecId;
private TextView fromTime;
private TextView toTime;
private TextView total;
private HourReport rowModelBean;
private HourReport rowBean;
private CheckBox billable;
private ArrayList<HourReport> list;
private HourReportCatalog catalog;
private Map<Integer, Integer>selectedItems;
private Map<Integer, Integer>selectedRoles;
public ListViewAdapter(Activity context, int resourcecId,
ArrayList<HourReport> list, HourReportCatalog catalog) {
super(context, resourcecId, list);
this.catalog = catalog;
ListViewAdapter.context = context;
this.resourcecId = resourcecId;
this.list = list;
selectedItems = new HashMap<Integer, Integer>();
selectedRoles = new HashMap<Integer, Integer>();
}
// event handler for delete button "-"
private OnClickListener delete = new OnClickListener() {
#Override
public void onClick(View deletBtnF) {
int myPosition = (Integer) deletBtnF.getTag();
HourReport r = list.remove(myPosition);
selectedItems.put(myPosition, 0);
selectedRoles.put(myPosition, 0);
r.setTimeFinished(null);
r.setTimeStarted(null);
r.setTaks(null);
r.setTotal(0.0);
r.setBillable(false);
r.setEngagementContractID(0);
list.add(myPosition, r);
notifyDataSetChanged();
if (r.getDateCreated() != null) {
Log.e("Listview adapter", "inside the if statement");
Long id = r.getHourReportID();
Log.e("", "date created" + r.getDateCreated());
catalog.deleteHourReport(r);
r.setDateCreated(null);
}
}
};
// event handler for textView which is responsible for defining dateFrom
Calendar c = Calendar.getInstance();
OnClickListener onClickLisOnDateFrom = new OnClickListener() {
#Override
public void onClick(View editField) {
Integer position1 = (Integer) editField.getTag();
TableRow parent = (TableRow) editField.getParent();
fromTime = (TextView) parent.findViewById(R.id.viewTextFrom);
total = (TextView) parent.findViewById(R.id.textViewShowsTotal);
rowBean = getModel(position1);
TimePickerDialog.OnTimeSetListener timeListener1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
String time = hour + ":" + minutes;
fromTime.setText(time);
setTimeFieldFrom(time);
String totalTime = totalHourCalculator();
total.setText(totalTime);
}
};
new TimePickerDialog(context, timeListener1,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true)
.show();
}
};
// event handler for textView which is responsible for defining dateTo
private OnClickListener onClickLisOnDateTo = new OnClickListener() {
#Override
public void onClick(View editField) {
Integer position1 = (Integer) editField.getTag();
Log.e("ListView - Timer ", "position: " + position1);
TableRow parent = (TableRow) editField.getParent();
toTime = (TextView) parent.findViewById(R.id.viewTextFrom);
total = (TextView) parent.findViewById(R.id.textViewShowsTotal);
rowBean = getModel(position1);
TimePickerDialog.OnTimeSetListener timeListener2 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
String time = hour + ":" + minutes;
toTime.setText(time);
setTimeFieldTo(time);
String totalTime = totalHourCalculator();
total.setText(totalTime);
}
};
new TimePickerDialog(context, timeListener2,
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true)
.show();
}
};
// event handler for check box
private OnClickListener checkBoxListener = new OnClickListener() {
#Override
public void onClick(View checkBox) {
Integer num = (Integer) checkBox.getTag();
rowBean = getModel(num);
if (rowBean.isBillable()) {
rowBean.setBillable(false);
} else {
rowBean.setBillable(true);
}
}
};
#Override
public View getView( int position, View convertView, ViewGroup parent) {
getHourReportList();
TextView deleteBtnV = null;
View row = convertView;
Spinner taskSpinner, roleSpinner;
TextView addReport;
final ViewHolder viewHolder;
if (row == null) {
LayoutInflater layoutInflater = context.getLayoutInflater();
row = layoutInflater.inflate(resourcecId, parent, false);
viewHolder = new ViewHolder(row);
fromTime = viewHolder.getFromTime();
deleteBtnV = viewHolder.getDeleteBtnVView();
deleteBtnV.setOnClickListener(delete);
billable = viewHolder.getCheckBox();
addReport = viewHolder.getAddButtonView();
// event handler for the button "+" which adds extra row
addReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Integer myPosition = (Integer) view.getTag();
HourReport report = list.get(myPosition);
HourReport nReport = new HourReport();
nReport.setClaimDate(report.getClaimDate());
nReport.setEmployeeID(report.getEmployeeID());
nReport.setBillable(false);
nReport.setEngagementContractID(0);
list.add(myPosition + 1, nReport);
notifyDataSetChanged();
}
});
viewHolder.adapter = new SpinerAdapter(context);
taskSpinner = viewHolder.getSpinnerTask();
roleSpinner = viewHolder.getSpinnerRole();
//event handler for the spinner
taskSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View spin,
int selected, long arg3) {
Spinner spinner = (Spinner) spin.getParent();
Integer myPosition = (Integer) spinner.getTag();
viewHolder.adapter.setSelected(selected);
String task = viewHolder.adapter.getSelectcetdTask();
long engmId = viewHolder.adapter.getSelectedTaskID();
rowBean = getModel(myPosition);
rowBean.setTaks(task);
rowBean.setEngagementContractID(engmId);
selectedItems.put(myPosition, selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
////event handler for the spinner
roleSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View spin,
int selectedRole, long arg3) {
Spinner spinner = (Spinner) spin.getParent();
Integer myPosition = (Integer) spinner.getTag();
selectedRoles.put(myPosition, selectedRole);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
fromTime = viewHolder.getFromTime();
toTime = viewHolder.getToTime();
fromTime.setOnClickListener(onClickLisOnDateFrom);
toTime.setOnClickListener(onClickLisOnDateTo);
billable.setOnClickListener(checkBoxListener);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) row.getTag();
fromTime = viewHolder.getFromTime();
toTime = viewHolder.getToTime();
taskSpinner = viewHolder.getSpinnerTask();
roleSpinner = viewHolder.getSpinnerRole();
total = viewHolder.getTotal();
billable = viewHolder.getCheckBox();
TextView date = viewHolder.getDate();
deleteBtnV = viewHolder.getDeleteBtnVView();
addReport = viewHolder.getAddButtonView();
}
HourReport model = getModel(position);
Integer selection = 0;
if (selectedItems.get(position) != null) {
selection = selectedItems.get(position);
}
int selectionR = 0;
if (selectedRoles.get(position) != null) {
selectionR = selectedRoles.get(position);
}
viewHolder.getFromTime().setText(
parseDateToString(model.getTimeStarted()));
viewHolder.getToTime().setText(
parseDateToString(model.getTimeFinished()));
viewHolder.getTotal().setText(
convertDoubleTotToStringTot(model.getTotal()));
viewHolder.getDate().setText(
parseDateToStringDDate(model.getClaimDate()));
viewHolder.getCheckBox().setChecked(model.isBillable());
Log.e("", "tag " + selection + " date " + model.getClaimDate());
viewHolder.taskSpinner.setSelection(selection);
viewHolder.roleSpinner.setSelection(selectionR);
fromTime.setTag(Integer.valueOf(position));
toTime.setTag(Integer.valueOf(position));
taskSpinner.setTag(Integer.valueOf(position));
roleSpinner.setTag(Integer.valueOf(position));
billable.setTag(Integer.valueOf(position));
deleteBtnV.setTag(Integer.valueOf(position));
addReport.setTag(Integer.valueOf(position));
return row;
}![here you have screen shoot of single row][1]
Create a single instance of OnClickListener (for example as an inner class) and assign this instance to every widget. If you need to know which row this widget belongs to, you can call setTag("pos", position) on that widget. By doing this you will be able to get position by calling view.getTag("pos") in onClick(View view) method of the listener. Hope this helps.
Related
This is my testfragment where i build the list based on a switch:
public class TestFragment extends Fragment {
public String Workshop;
public int NumberOfQuestions;
public Button SaveButton;
public TextView GradeView;
public String Grades;
private OnFragmentInteractionListener mListener;
public TestFragment() {}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle bundle){
View rootView = inflater.inflate(R.layout.questionscomplete,
container, false);
Workshop = getArguments().getString("Workshoptitle");
GradeView = ((TextView) rootView.findViewById(R.id.GradeView));
// Inflate the layout for this fragment
if (!Workshop.equals("Doodlz Drawing")) {
rootView = inflater.inflate(R.layout.fragment_test,
container, false);
final ListView lv1 = (ListView) rootView.findViewById(R.id.listview);
ArrayList image_details = getListData();
lv1.setAdapter(new CustomListAdapter(getActivity(), image_details));
SaveButton = ((Button) rootView.findViewById(R.id.Save));
SaveButton.setOnClickListener(Grading);
}
return rootView;
}
private ArrayList getListData() {
ArrayList<QuestionItem> results = new ArrayList<QuestionItem>();
switch (Workshop) {
case "Android Studio":
Workshop = "Android Studio";
QuestionItem[] Item1 = new QuestionItem[3];
QItem WS1 = new QItem();
NumberOfQuestions = Item1.length;
String[] WS1Q = WS1.getQuestions(Workshop, NumberOfQuestions);
String[] WS1QA = WS1.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item1[i] = new QuestionItem();
Item1[i].setQuestion(WS1Q[i]);
Item1[i].setAnswer1(WS1QA[i * 10 + 0]);
Item1[i].setAnswer2(WS1QA[i * 10 + 1]);
Item1[i].setAnswer3(WS1QA[i * 10 + 2]);
Item1[i].setAnswer4(WS1QA[i * 10 + 3]);
// Toast.makeText(getActivity(), Item1[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
results.add(Item1[i]);
}
break;
case "Java Basics":
Workshop = "Java Basics";
QuestionItem[] Item2 = new QuestionItem[5];
QItem WS2 = new QItem();
NumberOfQuestions = Item2.length;
String[] WS2Q = WS2.getQuestions(Workshop, NumberOfQuestions);
String[] WS2QA = WS2.getAnswers(Workshop);
for (int i = 0; i < NumberOfQuestions; i++) {
Item2[i] = new QuestionItem();
Item2[i].setQuestion(WS2Q[i]);
Item2[i].setAnswer1(WS2QA[i * 10 + 0]);
Item2[i].setAnswer2(WS2QA[i * 10 + 1]);
Item2[i].setAnswer3(WS2QA[i * 10 + 2]);
Item2[i].setAnswer4(WS2QA[i * 10 + 3]);
results.add(Item2[i]);
// Toast.makeText(getActivity(), Item2[i].GetAnswer(),
// Toast.LENGTH_LONG).show();
}
break;
My listadapter:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public String Answer;
public String[] Answers;
private ArrayList<QuestionItem> listData;
public CustomListAdapter(Context aContext, ArrayList<QuestionItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.questions, null);
holder = new ViewHolder(
);
holder.QuestionView = (TextView) convertView.findViewById(R.id.q);
holder.Answer1View = (TextView) convertView.findViewById(R.id.qa1);
holder.Answer2View = (TextView) convertView.findViewById(R.id.qa2);
holder.Answer3View = (TextView) convertView.findViewById(R.id.qa3);
holder.Answer4View = (TextView) convertView.findViewById(R.id.qa4);
//
holder.Answer1Button = (RadioButton) convertView.findViewById(R.id.qa1);
holder.Answer2Button = (RadioButton) convertView.findViewById(R.id.qa2);
holder.Answer3Button = (RadioButton) convertView.findViewById(R.id.qa3);
holder.Answer4Button = (RadioButton) convertView.findViewById(R.id.qa4);
holder.ButtonGroupView = (RadioGroup) convertView.findViewById(R.id.group);
convertView.setTag(holder);
holder.ButtonGroupView.getCheckedRadioButtonId();
holder.ButtonGroupView
.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
Integer pos = (Integer) group.getTag(); // To identify the Model object i get from the RadioGroup with getTag()
// an integer representing the actual position
QuestionItem element = listData.get(pos);
switch (checkedId) { //set the Model to hold the answer the user picked
case R.id.qa1:
element.setAnswer("1");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa2:
element.setAnswer("2");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa3:
element.setAnswer("3");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
case R.id.qa4:
element.setAnswer("4");
"Log.d(listData.get(pos).toString(), element.GetAnswer());
break;
default:
element.setAnswer(null); // Something was wrong set to the default
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
QuestionItem element = (QuestionItem) getItem(position);
holder.QuestionView.setText(listData.get(position).getQuestion());
holder.Answer1View.setText(listData.get(position).Getanswer1());
holder.Answer2View.setText(listData.get(position).Getanswer2());
holder.Answer3View.setText(listData.get(position).Getanswer3());
holder.Answer4View.setText(listData.get(position).Getanswer4());
holder.ButtonGroupView.setTag(new Integer(position)); // I passed the current position as a tag
return convertView;
}
//
class ViewHolder {
TextView t = null;
TextView QuestionView;
TextView Answer1View;
TextView Answer2View;
TextView Answer3View;
TextView Answer4View;
RadioButton Answer1Button, Answer2Button, Answer3Button, Answer4Button;
RadioGroup ButtonGroupView;
}}
My question Item:
public class QuestionItem {
private String Question;
private String Answer1;
private String Answer2;
private String Answer3;
private String Answer4;
private String Answer;
public String getQuestion() {
return Question;
}
public void setQuestion(String Question) {
this.Question = Question;
}
public String Getanswer1() {
return Answer1;
}
public void setAnswer1(String Answer1) {
this.Answer1 = Answer1;
}
public String Getanswer2() {
return Answer2;
}
public void setAnswer2(String Answer2) {
this.Answer2 = Answer2;
}
public String Getanswer3() {
return Answer3;
}
public void setAnswer3(String Answer3) {
this.Answer3 = Answer3;
}
public String Getanswer4() {
return Answer4;
}
public void setAnswer4(String Answer4) {
this.Answer4 = Answer4;
}
public String GetAnswer() {
return Answer;
}
public void setAnswer(String Answer) {
this.Answer = Answer;
}
}
I want to save all the answers and compare them to the right answers and save the score to be used as a variable in another fragment.
UPDATE: added "Log.d(listData.get(pos).toString(), element.GetAnswer());" And i can see it is storing the choses answers so how do i request them in the testfragment and check them
Ive tried several things but cannot find the solution. pls help:)?
I'm currently trying to diagnosis a bug where when a user is wanting to back out of the game activity using the back button it closes the window but doesn't seem to actually close the activity. The reason I think the activity isn't closing is because when a new game activity is started, the activity seems to call onFinish from CountDownTimer and close as if the time ran out when the timer in game shows there is still time left in the new game. Essentially I think my old activity is closing my new activity, even after the activity is no longer showing and should be closed based on my onBackPressed() method.
Here is my code:
public class Game extends Activity {
ImageButton position0;
ImageButton position1;
ImageButton position2;
ImageButton position3;
Button colorPosition;
RelativeLayout background;
Random rand = new Random();
int[] position = {0,1,2,3};
int score = 0;
int streak = 1;
int multi = 1;
int currentColor;
SharedPreferences gamePrefs;
boolean countDisable = true;
public static final String GAME_PREFS = "ColorMatchFile";
TextView scoreText;
TextView multiplierText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
scoreText = (TextView) findViewById(R.id.score);
multiplierText= (TextView) findViewById(R.id.multiplier);
background = (RelativeLayout) findViewById(R.id.background);
StartCount start_count = new StartCount(5000, 1000);
start_count.start();
colorPosition = (Button)findViewById(R.id.colorPosition);
position0 = (ImageButton)findViewById(R.id.position0);
position1 = (ImageButton)findViewById(R.id.position1);
position2 = (ImageButton)findViewById(R.id.position2);
position3 = (ImageButton)findViewById(R.id.position3);
if(savedInstanceState != null){
int exScore = savedInstanceState.getInt("score");
scoreText.setText("Score: "+ exScore);
}
#Override
public void onBackPressed() {
setHighScore();
finish();
Intent intent = new Intent(getApplicationContext(), score_screen.class);
startActivity(intent);
super.onBackPressed();
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture,long countDownInterval){
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Times Up!");
Thread thread = new Thread();
try {
thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
setHighScore();
finish();
Intent intent = new Intent(getApplicationContext(), score_screen.class);
startActivity(intent);
}
#Override
public void onTick(long millisUntilFinished){
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Left: " + millisUntilFinished/1000);
}
}
public class StartCount extends CountDownTimer{
public StartCount(long millisInFuture,long countDownInterval){
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Begin!");
MyCount counter = new MyCount(30000, 1000);
currentColor = rand.nextInt(4);
setCurrentColor(currentColor);
countDisable = false;
counter.start();
}
#Override
public void onTick(long millisUntilFinished){
final TextView time = (TextView) findViewById(R.id.time);
time.setText("Start In: " + millisUntilFinished/1000);
showCurrentPosition();
}
}
Well the problem was I wasn't turning the counter for MyCount off. Here is how I solved it:
#Override
public void onBackPressed() {
setHighScore();
counter.cancel();
this.finish();
Intent intent = new Intent(getApplicationContext(), score_screen.class);
startActivity(intent);
}
Note I had to use counter.cancel() and make counter a global variable.
First of all I'm sorry for my bad English :X
Iam quite a newbie in Android App development and Iam about to develope an app which gives the user informations like free park-places in town.
The app is based on Google Maps.
My Problem:
My app starts and shows a Google Maps Layout. Over an ExpandableListView the User can open a overview about the Parking-Locations.
If the user click on a Child Item in the ExpListView a new Cluster item should be generated at the MapsLayout.
How can I give the OnClick data to the MainActivity? I want that the MainActivity 'knew' which Item is clicked by the User!
Im glad about every answer :)
public class MyExpandableAdapter extends BaseExpandableListAdapter{
private Activity activity;
private ArrayList<Object> childtems;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child;
// constructor
public MyExpandableAdapter(ArrayList<String> parents, ArrayList<Object> childern)
{
this.parentItems = parents;
this.childtems = childern;
}
public void setInflater(LayoutInflater inflater, Activity activity)
{
this.inflater = inflater;
this.activity = activity;
}
// method getChildView is called automatically for each child view.
// Implement this method as per your requirement
#Override
public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
child = (ArrayList<String>) childtems.get(groupPosition);
TextView textView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_view, null);
}
// get the textView reference and set the value
textView = (TextView) convertView.findViewById(R.id.textViewChild);
textView.setText(child.get(childPosition));
// set the ClickListener to handle the click event on child item
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(activity, child.get(childPosition),
Toast.LENGTH_SHORT).show();
//Tried to insert connection to MapsActivity but doesnt work!
}
});
return convertView;
}
// method getGroupView is called automatically for each parent item
// Implement this method as per your requirement
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
if (convertView == null) {
convertView = inflater.inflate(R.layout.parent_view, null);
}
((CheckedTextView) convertView).setText(parentItems.get(groupPosition));
((CheckedTextView) convertView).setChecked(isExpanded);
return convertView;
}
#Override
public Object getChild(int groupPosition, int childPosition)
{
return null;
}
#Override
public long getChildId(int groupPosition, int childPosition)
{
return 0;
}
#Override
public int getChildrenCount(int groupPosition)
{
return ((ArrayList<String>) childtems.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition)
{
return null;
}
#Override
public int getGroupCount()
{
return parentItems.size();
}
#Override
public void onGroupCollapsed(int groupPosition)
{
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition)
{
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
return false;
}
}
MapsActivity (Main)
public class MapsActivity extends FragmentActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private ClusterManager<MyItem> mClustermanager ;
private ArrayList<String> parentItems = new ArrayList<String>();
private ArrayList<Object> childItems = new ArrayList<Object>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpClusterer();
// Create Expandable List and set it's properties
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandableListView);
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
// Set the Items of Parent
setGroupParents();
// Set The Child Data
setChildData();
// Create the Adapter
MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
// Set the Adapter to expandableList
expandableList.setAdapter(adapter);
// expandableList.setOnChildClickListener();
}
// method to add parent Items
public void setGroupParents()
{
parentItems.add("Parkhäuser");
}
public void setChildData()
{
ArrayList<String> child = new ArrayList<String>();
child = new ArrayList<String>();
child.add("Park1");
child.add("Park2");
child.add("Park3");
child.add("Park4");
childItems.add(child);
}
private void setUpClusterer()
{
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(47.99481, 7.84856), 10 )) ;
//Initialisierung des Managers mit dem Context (this) und der Map
//Activity erbt von Context deswegen können wir dem Konstruktor 'this' mitgeben
mClustermanager = new ClusterManager<MyItem>(this, ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap() );
//Zeigt der Map die Listener des ClusterManagers
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().setOnCameraChangeListener((mClustermanager));
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap().setOnMarkerClickListener(mClustermanager);
//Hinzufügen der Markierungen zum Cluster Manager
addItems() ;
}
private void addItems(){
//Startkoordinaten des ersten Markers --> Bahnhofsgarage
double lat = 47.99673 ;
double lng = 7.84152 ;
//Hinzufügen von 10 weiteren Punkten
for(int i = 1; i <14; i++){
if(i==1)
{ //Konzerthaus
lat = 47.99602 ;
lng = 7.84220;
}
if(i==2){
//Volksbank
lat = 47.99783 ;
lng = 7.84322;
}
if(i==3){
//am Bahnhof
lat = 47.99892 ;
lng = 7.84310;
}
if(i==4){
//Uni-FMF/Vf
lat = 48.00135 ;
lng = 7.84481;
}
if(i==5){
//unterlinden
lat = 47.99811 ;
lng = 7.84876;
}
if(i==6){
//schwarzwaldcity
lat = 47.99760 ;
lng = 7.85090;
}
if(i==7){
//Rotteckring
lat = 47.99618 ;
lng = 7.84732;
}
if(i==8){
//Am Zähringer Tor
lat = 47.99921 ;
lng = 7.85350;
}if(i==9){
//Karlsbau
lat = 47.99757 ;
lng = 7.85366;
}if(i==10){
//Landratsamt
lat = 47.99969 ;
lng = 7.85758;
}if(i==11){
//Schlossberg
lat = 47.99654 ;
lng = 7.85758;
}if(i==12){
//Schwabentor
lat = 47.99054 ;
lng = 7.85833;
}if(i==13){
//Am Martinstor
lat = 47.99281 ;
lng = 7.84715;
}if(i==14){
//Uni Kolleg Gebäude
lat = 47.98797 ;
lng = 7.87129;
}
MyItem offsetItem = new MyItem(lat,lng) ;
mClustermanager.addItem(offsetItem);
}
}
}
Solved! After research I make ExpandableAdpater an inner class of MapsActivity! Now i can put data between both classes and use Methods also!
I have a listview in my main activity.In each row i have a image view,when i click that image view QuickAction(Like popover in ios) will appears.My request is, I want to setText the text from listview to the another Activity's edittext when i click the action item in the quick action.Please help..
Here is my Main Activity
public class ExampleActivity extends Activity {
private static final int ID_UP = 1;
private static final int ID_DOWN = 2;
private static final int ID_SEARCH = 3;
private static final int ID_INFO = 4;
private QuickAction quickAction;
private ActionItem nextItem;
private ActionItem prevItem;
private ActionItem searchItem;
private ListView view;
private ContactsAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (ListView) findViewById(R.id.listView1);
final Weather weather_data[] = new Weather[] { new Weather(R.drawable.icon, "Cloudy"),
new Weather(R.drawable.icon, "Showers"),
new Weather(R.drawable.icon, "Snow"),
new Weather(R.drawable.icon, "Storm"),
new Weather(R.drawable.icon, "Sunny")
};
adapter = new ContactsAdapter(this, R.layout.main1,
weather_data);
}
void functiontorun(View view1) {
quickAction = new QuickAction(this,QuickAction.HORIZONTAL);
nextItem = new ActionItem(ID_DOWN, "Next", getResources().getDrawable(
R.drawable.menu_down_arrow));
prevItem = new ActionItem(ID_UP, "Prev", getResources().getDrawable(
R.drawable.menu_up_arrow));
searchItem = new ActionItem(ID_SEARCH, "Find", getResources()
.getDrawable(R.drawable.menu_search));
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
prevItem.setSticky(true);
nextItem.setSticky(true);
// add action items into QuickAction
quickAction.addActionItem(nextItem);
quickAction.addActionItem(prevItem);
quickAction.addActionItem(searchItem);
// Set listener for action item clicked
final int position1 = view.getPositionForView(view1);
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
if (actionId == ID_SEARCH) {
Intent i=new Intent(ExampleActivity.this,Second.class);
i.putExtra("position",position1 );
Log.v("position","po" +position1);
startActivity(i);
} else if (actionId == ID_INFO) {
Toast.makeText(getApplicationContext(),
"I have no info this time",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
actionItem.getTitle() + " selected",
Toast.LENGTH_SHORT).show();
}
}
});
quickAction.show(view1);
}
}
And my another activity
public class Second extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
EditText d1=(EditText) findViewById(R.id.editText1);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
final int position = (Integer) bundle.get("position");
Log.v("position","po1 " +position);
ArrayList<Weather> array = new ArrayList<Weather>();
Log.v("position","po1 " +array);
}
}
}
contacts adapter:
public class ContactsAdapter extends ArrayAdapter{
Context context;
int layoutResourceId;
Weather data[] = null;
public ContactsAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imageView1);
holder.imgIcon.findViewById(R.id.imageView1).setOnClickListener(mBuyButtonClickListener);
holder.txtTitle = (TextView)row.findViewById(R.id.textView1);
//((ImageView) row.findViewById(R.id.im)).setOnClickListener(mBuyButtonClickListener);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
((ExampleActivity) context).functiontorun(v);
}
};
}
private OnClickListener mBuyButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
WeatherHolder holder = (WeatherHolder) v.getTag;
String string = holder.txtTitle .getText();
((ExampleActivity) context).functiontorun(string);
}
};
just pass the string to your activity and change the parameter of the functiontorun as string
I am trying to make a straight ended connection between widgets.But when I am doing so, the orientation of my connector is coming wrong.Its always coming parallel to the required one.Also , it is independent of the connecting widgets i.e when I move my widget, my connector does not move.Snippet of my code is given as :
Link to snapshot of the problem: http://goo.gl/JUEmJ
public class DragNDropPage {
SyncCurrentUser cu = SyncCurrentUser.getUser();
private AbsolutePanel area = new AbsolutePanel();
HorizontalPanel toolsPanel = new HorizontalPanel();
AbsolutePanel canvas = new AbsolutePanel();
DragController toolboxDragController;
Label startLabel = new Label("START");
Label stopLabel = new Label("STOP");
Label activityLabel = new Label("ACTIVITY");
Label processLabel = new Label("PROCESS");
Button stopDrag = new Button("Done Dragging");
Button saveButton = new Button("Save");
PickupDragController dragController = new PickupDragController(area, true);
AbsolutePositionDropController dropController = new AbsolutePositionDropController(area);
private List<Widget> selected = new ArrayList<Widget>();
private List<Widget> onCanvas = new ArrayList<Widget>();
private List<Connection> connections = new ArrayList<Connection>();
private CActivity[] aItems;
private CProcess[] pItems;
MyHandler handler = new MyHandler();
int mouseX,mouseY;
String style;
public DragNDropPage() {
toolboxDragController = new ToolboxDragController(dropController, dragController);
RootPanel.get("rightbar").add(area);
area.setSize("575px", "461px");
area.add(toolsPanel);
toolsPanel.setSize("575px", "37px");
toolsPanel.add(startLabel);
startLabel.setSize("76px", "37px");
toolboxDragController.makeDraggable(startLabel);
toolsPanel.add(stopLabel);
stopLabel.setSize("66px", "37px");
toolboxDragController.makeDraggable(stopLabel);
toolsPanel.add(activityLabel);
activityLabel.setSize("82px", "36px");
toolboxDragController.makeDraggable(activityLabel);
toolsPanel.add(processLabel);
processLabel.setSize("85px", "36px");
toolboxDragController.makeDraggable(processLabel);
stopDrag.addClickHandler(handler);
toolsPanel.add(stopDrag);
stopDrag.setWidth("114px");
saveButton.addClickHandler(handler);
toolsPanel.add(saveButton);
area.add(canvas, 0, 36);
canvas.setSize("575px", "425px");
Event.addNativePreviewHandler(new Event.NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
//46 is the key code for Delete Button
if(event.getNativeEvent().getKeyCode() == 46 && !selected.isEmpty()) {
for (Iterator<Widget> i = selected.listIterator(); i.hasNext();) {
Widget w = (Widget) i.next();
UIObjectConnector.unwrap(w);
i.remove();
w.removeFromParent();
onCanvas.remove(i);
}
}
}
});
aItems = cu.currentUser.getcActivity();
pItems = cu.currentUser.getcProcess();
}
private class ToolboxDragController extends PickupDragController {
public ToolboxDragController(final DropController dropController, final DragController nodesDragController) {
super(area ,false);
setBehaviorDragProxy(true);
registerDropController(dropController);
addDragHandler(new DragHandlerAdapter(){
public void onPreviewDragEnd(DragEndEvent event) throws VetoDragException {
Widget node = (Widget) event.getSource();
int left = event.getContext().desiredDraggableX;
int top = event.getContext().desiredDraggableY;
AbsolutePanel panel = (AbsolutePanel) dropController.getDropTarget();
createConnector((Label) node, panel, left, top);
throw new VetoDragException();
}
});
}
}
protected UIObjectConnector createConnector(Label proxy, AbsolutePanel panel, int left, int top) {
Widget w;
String str = proxy.getText();
if(str.equals("START") || str.equals("STOP")){
w = new Label(proxy.getText()){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
w.getElement().setClassName("dnd-start-stop");
}
else{
w = new ListBox(){
public void onBrowserEvent(Event event) {
if( DOM.eventGetType(event) == 4
&& DOM.eventGetCtrlKey(event)){
select(this);
}
super.onBrowserEvent(event);
}
};
if(str.equals("ACTIVITY")){
getAItems((ListBox)w);
//w.getElement().addClassName("dnd-activity");
}
else if(str.equals("PROCESS")){
getPItems((ListBox)w);
//w.getElement().addClassName("dnd-process");
}
}
onCanvas.add(w);
left -= panel.getAbsoluteLeft();
top -= panel.getAbsoluteTop();
//panel.add(w,10,10);
panel.add(w, left, top);
dragController.makeDraggable(w);
return UIObjectConnector.wrap(w);
}
private void getAItems(ListBox w) {
for(int i=0;i<aItems.length;i++)
w.addItem(aItems[i].getActivityName());
}
private void getPItems(ListBox w) {
/*for(int i=0;i<pItems.length;i++)
w.addItem(pItems[i].getProcessName());*/
w.addItem("Process1");
}
protected void select(Widget w){
if(selected.isEmpty()) {
selected.add(w);
w.getElement().addClassName("color-green");
} else if(selected.contains(w)){
selected.remove(w);
w.getElement().removeClassName("color-green");
} else if(selected.size() == 1) {
Widget w2 = (Widget) selected.get(0);
connect(UIObjectConnector.getWrapper(w2), UIObjectConnector.getWrapper(w));
selected.clear();
}
}
protected void connect(Connector a, Connector b) {
//System.out.println(a.getLeft());
//System.out.println(b.getLeft());
add(new StraightTwoEndedConnection(a,b));
}
private void add(StraightTwoEndedConnection c) {
canvas.add(c);
connections.add(c);
c.update();
}
protected void remove(Connection c) {
connections.remove(c);
}
class MyHandler implements ClickHandler{
#Override
public void onClick(ClickEvent event) {
Button name = (Button) event.getSource();
if(name.equals(stopDrag)){
if(name.getText().equals("Done Dragging")){
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeNotDraggable(w);
}
name.setText("Continue");
}
else {
for(Iterator<Widget> i = onCanvas.listIterator();i.hasNext();){
Widget w = (Widget) i.next();
dragController.makeDraggable(w);
}
name.setText("Done Dragging");
}
}
else{
}
}
}
}
I know this is quite old, but I was having similar issues with the gwt-connector library.
The connectors will not appear in the correct placement if you are using standards mode. Use quirks mode instead.
Additionally, you need to manually perform a connector.update() while your dnd components are being dragged (in your drag listener) for the connection to move with the endpoint while you are dragging.